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
- class Vehicle (speed : Int){
- val mph :Int = speed
- def race() = println("Racing")
- }
- class Car (speed : Int) extends Vehicle(speed) {
- override val mph: Int= speed
- override def race() = println("Racing Car")
- }
- class Bike(speed : Int) extends Vehicle(speed) {
- override val mph: Int = speed
- override def race() = println("Racing Bike")
- }
- trait flying {
- def fly() = println("flying")
- }
- trait gliding {
- def glide() = println("gliding")
- }
- class Batmobile(speed : Int) extends Vehicle(speed) with flying with gliding{
- override val mph: Int = speed
- override def race() = println("Racing Batmobile")
- override def fly() = println("Flying Batmobile")
- override def glide() = println("Gliding Batmobile")
- }
- object Vehicle {
- def main(args: Array[String]) {
- val vehicle1 = new Car(200)