Learn Java for Web Development

(Tina Meador) #1

432 APPENDIX C: Introduction to Scala


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. class Bike(speed : Int) extends Vehicle(speed) {

  10. override val mph: Int = speed

  11. override def race() = println("Racing Bike")



  12. }

  13. trait flying {

  14. def fly() = println("flying")

  15. }



  16. trait gliding {

  17. def glide() = println("gliding")

  18. }



  19. class Batmobile(speed : Int) extends Vehicle(speed) with flying with gliding{

  20. override val mph: Int = speed

  21. override def race() = println("Racing Batmobile")

  22. override def fly() = println("Flying Batmobile")

  23. override def glide() = println("Gliding Batmobile")



  24. }

  25. object Vehicle {

  26. def main(args: Array[String]) {

  27. val vehicle1 = new Car(200)

Free download pdf