tags:

views:

1034

answers:

4

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
Does this have any practical implications, or does it only make the code easier to understand?
Ralf
I am just referring to code understandability.
peter p
+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
Hope you are not implying that traits cannot contain behavior. Both can contain implementation code.
Mitch Blevins
@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
+9  A: 

I can think of two differences

  1. 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
  2. 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
+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