Using the same example as the first tutorial, let's assume we have a trait for a WorkVehicle, as follows.
trait WorkVehicle { def towWeight: Integer = { return 2500 } }
This trait has a default/concrete implementation for the towWeight method. Next, let's consider a class for a PersonalVehicle that extends a base abstract class called Vehicle. Note that the class itself does not mix-in the WorkVehicle trait.
abstract class Vehicle class PersonalVehicle extends Vehicle
Rather than creating a new class that mixes-in the WorkVehicle trait, we can do this at the time the class is created, like such.
val myWorkVehicle = new PersonalVehicle with WorkVehicle
This is a powerful feature. It allows us to mix-in traits for individual objects, only when needed, rather than doing it at the time that the class is designed. Very cool!
Your Scala blog posts are easy to understand. I appreciate your work.
ReplyDeleteThank you