In Scala, what is the advantage of using an abstract class instead of a trait (apart from performance)? At first glance it seems like abstract classes can be replaced by traits in most cases.
+1
A:
When extending an abstract class, this shows that the subclass is of a similar kind. This is not neccessarily the case when using traits, I think.
peter p
2010-01-02 09:23:36
Does this have any practical implications, or does it only make the code easier to understand?
Ralf
2010-01-02 09:28:58
I am just referring to code understandability.
peter p
2010-01-02 09:44:20
+2
A:
Abstract classes can contain behaviour - They can parameterized with constructor args (which traits can't) and represent a working entity. Traits instead just represent a single feature, an interface of one functionality.
Dario
2010-01-02 09:34:43
Hope you are not implying that traits cannot contain behavior. Both can contain implementation code.
Mitch Blevins
2010-01-02 19:05:51
@Mitch Blevins: Of course not. They can contain code, but when you define `trait Enumerable` with lots of helper functions, I wouldn't call them *behaviour* but just functionality connected with one feature.
Dario
2010-01-02 19:25:49
+9
A:
I can think of two differences
- 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
- 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
Mushtaq Ahmed
2010-01-02 11:53:57
+3
A:
For whatever it is worth, Odersky et al's Programming in Scala recommends that, when you doubt, you use traits. You can always change them into abstract classes later on if needed.
Daniel
2010-01-02 14:45:44