O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Selective Mixins

In the previous example, we mixed the trait Friend into the Dog class. Thus, any instance of the Dog class can now be treated as a Friend; that is, all Dogs are Friends.

That may be too sweeping in some cases. If we desire, we could mix traits selectively at an instance level. In that case, we can treat a specific instance of a class as a trait. Let’s look at an example:

UsingTraits/Cat.scala
 
class​ Cat(​val​ name: ​String​) ​extends​ Animal

Cat does not mix in the Friend trait, so we can’t treat an instance of Cat as a Friend. Any attempts to do so, as we can see here, will result in compilation errors:

UsingTraits/UseCat.scala
 
object​ UseCat ​extends​ App {
 
def​ useFriend(friend: Friend) = friend.listen
 
 
val​ alf ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required