Learn Java for Web Development

(Tina Meador) #1

430 APPENDIX C: Introduction to Scala


Save Listing C-12 in the file vehicle.scala and compile it using the following:



scalac vehicle.scala



Now you can enter the REPL using the scala command and create the vehicle object,
as shown here:


scala> val vehicle1 = new Car(200)


With this command, Scala creates the vehicle1 object, as shown here:


vehicle1: Car = Car@19a8942


Now you can use this vehicle1 object created by Scala to access the speed of Car.


scala> vehicle1.mph


The Scala REPL emits the speed of Car, as shown here:


res1: Int = 200


In the similar manner, you can execute the race() method of vehicle1, as shown here:


scala>vehicle1.race()


The Scala interpreter emits the output, as shown here:


Racing Car


Now you can create the Bike object and access its property and method, as shown here:


scala> val vehicle2 = new Bike(100)


vehicle2: Bike = Bike@b7ad3


scala>vehicle2.mph


res4: Int = 100


scala> vehicle2.race()


Racing Bike

Free download pdf