61

I see that traits in Scala are similar to interfaces in Java (but interfaces in Java extend other interfaces, they don't extend a class). I saw an example on SO about traits usage where a trait extends a class.

What is the purpose of this? Why can traits extend classes?

Community
  • 1
  • 1
Raj
  • 4,342
  • 9
  • 40
  • 45
  • 1
    If you read the answer you linked, you'll see that traits are very dissimilar to interfaces, since they can contain implementations. – Jan Hudec Oct 12 '12 at 08:26
  • 2
    You might also be interested in the difference between trait inheritance and self-type annotations: http://stackoverflow.com/questions/1990948/what-is-the-difference-between-scala-self-types-and-trait-subclasses – Malte Schwerhoff Oct 12 '12 at 08:29
  • Yes, I understood the point that traits, unlike interfaces can contain partial implementation of methods, but I wasn't sure about the purpose of traits extending classes (as explained in the example) – Raj Oct 12 '12 at 08:30

1 Answers1

77

Yes they can, a trait that extends a class puts a restriction on what classes can extend that trait - namely, all classes that mix-in that trait must extend that class.

scala> class Foo
defined class Foo

scala> trait FooTrait extends Foo
defined trait FooTrait

scala> val good = new Foo with FooTrait
good: Foo with FooTrait = $anon$1@773d3f62

scala> class Bar
defined class Bar

scala> val bad = new Bar with FooTrait
<console>:10: error: illegal inheritance; superclass Bar
 is not a subclass of the superclass Foo
 of the mixin trait FooTrait
       val bad = new Bar with FooTrait
                              ^
Taky
  • 5,284
  • 1
  • 20
  • 29
adelbertc
  • 7,270
  • 11
  • 47
  • 70
  • 15
    Interesting. But you can also restrict the classes into which a trait can be mixed by putting a type constraint on the self-type, e.g. `trait FooTrait { self:Foo => }`. When would you use one technique versus the other? – AmigoNico Apr 10 '13 at 05:09
  • Scala gets pretty crazy with all the typing business. I can definitely see this could be pretty useful, but can anyone give any concrete examples? – leinaD_natipaC Dec 15 '13 at 17:49
  • 3
    @AmigoNico [here](http://stackoverflow.com/q/36945333/2032064) is one example when you may prefer inheriting from a class. – Mifeet May 23 '16 at 08:33