- 首先你需要重用才需要考虑这个问题。If the behavior will not be reused, then make it a concrete class.
- 优先使用特质。一个类扩展多个特质是很方便的,但却只能扩展一个抽象类。
If you still do not know, after considering the above, then start by making it as a trait. You can always change it later, and in general using a trait keeps more options open.
- 优先使用trait
- multiple, unrelated classes, make it a trait.
- If outside clients will only call into the behavior, instead of inheriting from it, then using a trait is fine.
- 优先使用abstract class
- 如果你需要构造函数参数,使用抽象类。因为抽象类可以定义带参数的构造函数,而特质不行。例如,你不能说
trait t(i: Int) {}
,参数i
是非法的。- Abstract classes can have constructor parameters as well as type parameters.
- Traits can have only type parameters. There was some discussion that in future even traits can have constructor parameters
- 对于与java互动:优先abstract class
- Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers.
- Traits are fully interoperable only if they do not contain any implementation code
- 以 compiled form分布的,有外部其他类继承
- The issue is that when a trait gains or loses a member, any classes that inherit from it must be recompiled, even if they have not changed.
- 需要高效率--不一定,在肯定trait导致bottleneck时可以使用abstract class
- in classes,
super
calls are statically bound, in traits, they are dynamically bound.- If you write
super.toString
in a class, you know exactly which method implementation will be invoked. - When you write the same thing in a trait, however, the method implementation to invoke for the super call is undefined when you define the trait.
- If you write
REFERENCE
stackoverflow: Scala特质 vs 抽象类 , 抽象类和特质的区别, and Scala编程: 用特质,还是不用特质?
http://www.artima.com/pins1ed/traits.html
时间: 2024-11-10 18:40:03