views:

382

answers:

5

What is the conceptual difference between abstract classes and traits?

A: 

Here's a reference on abstract types:

http://www.scala-lang.org/node/105

Here is a reference on Traits:

http://www.scala-lang.org/node/126

Tony
+1  A: 

Traits(in Scala at least) system has an explicit way of declaring parent priority in subclass to avoid typical problems associated with multiple inheritance ie. conflicts with inherited methods having same signature.

Traits are akin to Java interfaces, but are allowed to have method implementations.

Illotus
+2  A: 

Conceptually, a trait is a component of a class, not a class by itself. As such, it typically does not have constructors, and it is not meant to "stand by itself".

I suggest using an abstract class when it has an independent meaning, and traits when you just want to add functionality in an object-oriented manner. If you're not sure between the two, you might find that if all your methods revolve around doing a single thing, you probably want a trait.

For a (non-language-specific) example, if your Employee should extend both "Person" and "Cloneable", make Person a base class and Cloneable a trait.

Oak
I would say that when all the methods revolve around doing a single thing, your design is okay (Single responsibility principle: http://en.wikipedia.org/wiki/Single_responsibility_principle). Otherwise the design should be a defendable compromise.
Thomas Jung
You're right, I clarified my answer a little.
Oak
+5  A: 

One aspect of traits is that they are a stackable. Allowing a constrainted form of AOP (around advice).

trait A{
    def a = 1
}

trait X extends A{
    override def a = {
        println("X")
        super.a
    }
}  


trait Y extends A{
    override def a = {
        println("Y")
        super.a
    }
}

scala> val xy = new AnyRef with X with Y
xy: java.lang.Object with X with Y = $anon$1@6e9b6a
scala> xy.a
Y
X
res0: Int = 1

scala> val yx = new AnyRef with Y with X
yx: java.lang.Object with Y with X = $anon$1@188c838
scala> yx.a
X
Y
res1: Int = 1

The resolution of super reflects the linearization of the inheritance hierarchy.

Thomas Jung
+5  A: 

A class can only extend one superclass, and thus, only one abstract class. If you want to compose several classes the Scala way is to use mixin class composition: you combine an (optional) superclass, your own member definitions and one or more traits. A trait is restricted in comparison to classes in that it cannot have constructor parameters (compare the scala reference manual).

The restrictions of traits in comparison to classes are introduced to avoid typical problems with multiple inheritance. There are more or less complicated rules with respect to the inheritance hierarchy; it might be best to avoid a hierarchy where this actually matters. ;-)

hstoerr