Why can a Scala trait extend a class?

ScalaTraits

Scala Problem Overview


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?

Scala Solutions


Solution 1 - Scala

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
                              ^

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRajView Question on Stackoverflow
Solution 1 - ScalaadelbertcView Answer on Stackoverflow