APPENDIX C: Introduction to Scala 429
Classes
Classes in Scala are declared very much like Java classes. One difference is that Scala classes can
have parameters, as illustrated in Listing C-10.
Listing C-10. Scala Class with Parameters
class Vehicle (speed : Int){
val mph :Int = speed
def race() = println("Racing")
}
The Vehicle class takes one argument, which is the speed of the vehicle. This argument must
be passed when creating an instance of class Vehicle, as follows: new Vehicle(100). The class
contains one method, called race().
Extending a Class
It is possible to override methods inherited from a superclass in Scala, as illustrated in Listing C-11.
Listing C-11. Extending a Scala Class
- class Car (speed : Int) extends Vehicle(speed) {
- override val mph: Int= speed
- override def race() = println("Racing Car")
- }
Line 1: The Car class extends the Vehicle class using the keyword extends.
Lines 2 to 3: The field mph and the method race() need to be overridden using
the keyword override.
Listing C-12 illustrates another class called Bike that extends Vehicle.
Listing C-12. Extending a Scala Class
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")
}