Java Reference
In-Depth Information
scala> val vehicleList = List(vehicle1, vehicle2, vehicle3)
vehicleList: List[Vehicle] = List(Car@562791, Bike@e80317, Batmobile@374ed5)
scala> val fastestVehicle = vehicleList.maxBy(_.mph)
fastestVehicle: Vehicle = Batmobile@374ed5
Singleton Objects
Scala does not have static members. Instead, Scala has singleton objects. A singleton object
definition looks like a class definition, except instead of the keyword class you use the keyword
object . A singleton is a class that can have only one instance. Listing C-15 illustrates how to use the
singleton object in an application.
Listing C-15. Using a Singleton Object in an Application
1. class Vehicle (speed : Int){
2. val mph :Int = speed
3. def race() = println("Racing")
4. }
5. class Car (speed : Int) extends Vehicle(speed) {
6. override val mph: Int= speed
7. override def race() = println("Racing Car")
8.
9. }
10. class Bike(speed : Int) extends Vehicle(speed) {
11. override val mph: Int = speed
12. override def race() = println("Racing Bike")
13.
14. }
15. trait flying {
16. def fly() = println("flying")
17. }
18.
19. trait gliding {
20. def glide() = println("gliding")
21. }
22.
23. class Batmobile(speed : Int) extends Vehicle(speed) with flying with gliding{
24. override val mph: Int = speed
25. override def race() = println("Racing Batmobile")
26. override def fly() = println("Flying Batmobile")
27. override def glide() = println("Gliding Batmobile")
28.
29. }
30. object Vehicle {
31. def main(args: Array[String]) {
32. val vehicle1 = new Car(200)
 
Search WWH ::




Custom Search