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 ... |
Get Pragmatic Scala now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.