Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a Scala trait extend a class?

Tags:

scala

traits

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?

like image 457
Raj Avatar asked Oct 12 '12 08:10

Raj


People also ask

Can a trait extend a class 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 .

Can a trait extend an abstract class Scala?

Although Scala has abstract classes, it's much more common to use traits than abstract classes to implement base behavior. A class can extend only one abstract class, but it can implement multiple traits, so using traits is more flexible.

How do traits work in Scala?

Traits are used to define object types by specifying the signature of the supported methods. Scala also allows traits to be partially implemented but traits may not have constructor parameters. A trait definition looks just like a class definition except that it uses the keyword trait.

Can object extends trait Scala?

Traits are used to share interfaces and fields between classes. They are similar to Java 8's interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.


1 Answers

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                               ^ 
like image 142
adelbertc Avatar answered Sep 20 '22 13:09

adelbertc