Java Reference
In-Depth Information
Traits
Say you want to add another class to your vehicle hierarchy. This time you want to add a batmobile.
A batmobile can race, glide, and fly. But you cannot add glide and fly methods to the Vehicle class
because in a nonfictional world, Car and Bike do not glide or fly. Not yet at least. So, if you want to
add Batmobile to your vehicle hierarchy, you can use a trait . Traits are like interfaces in Java that can
also contain code. In Scala, when a class inherits from a trait, it implements the interface of the trait
and inherits all the code contained in the trait. Listing C-13 shows flying and gliding traits.
Listing C-13. Scala Traits
trait flying {
def fly() = println("flying")
}
trait gliding {
def gliding() = println("gliding")
}
Now you can create the Batmobile class that extends Vehicle class along with the flying and
gliding traits, as shown in Listing C-14.
Listing C-14. Using Traits
1. Batmobile(speed : Int) extends Vehicle(speed) with flying with gliding{
2. override val mph: Int = speed
3. override def race() = println("Racing Batmobile")
4. override def fly() = println("Flying Batmobile")
5. override def glide() = println("Gliding Batmobile")
6.
7. }
You can now create a batmobile in the REPL, as illustrated here:
scala> val vehicle3 = new Batmobile(300)
vehicle3: Batmobile = Batmobile@374ed5
Now you can access the fly() method of Batmobile , as illustrated here:
scala> vehicle3.fly()
Flying Batmobile
Create a list of vehicles, and then you can use the maxBy() method provided by the Scala collections
library to find the fastest vehicle in the list.
 
Search WWH ::




Custom Search