package withextends.diff /** * Created by jack on 2017/8/1. */ trait Abstract { type T def gett(x: T): T def init: T } abstract class A { val v: String def m: String } // class ab extends A with Abstract{ override val v: String = _ override def m: String = "method" override type T = String override def gett(x: String): String = { this.m } override def init: String = "init" } class wes { } object Test extends App { val x = new ab val y = new wes with Abstract { override type T = this.type override def gett(x: this.type): this.type = ??? override def init: this.type = ??? } //compile error /*val z = new wes extends A { }*/ type y = ab with A //compile error /*type z = ab extens A*/ }
总结一下extends和with的区别:
1、无论是继承abstract class或者混入trait,对于一个要实现的类来说,必须先用extends,剩下的用with,否则编译的时候就会出错
当同时实现abstract class和trait的时候,abstract class必须在前,而trait必须在后,如果仅实现其一的话,只可以用extends
2、当直接new一个实现了trait的对象的时候的时候是可以使用with关键字的
3、T with U可以是一个新的type,但是T extends U并不是一个新的类型