Learn Java for Web Development

(Tina Meador) #1
APPENDIX C: Introduction to Scala 433


  1. val vehicle2 = new Bike(100)

  2. val vehicle3 = new Batmobile(300)



  3. val vehicleList = List(vehicle1, vehicle2, vehicle3)

  4. val fastestVehicle = vehicleList.maxBy(_.mph)



  5. printVehicle



  6. def printVehicle{

  7. println ("speed of Bike : " + vehicle1.mph);

  8. println ("speed of Car : " + vehicle2.mph);

  9. println ("speed of Batmobile : " + vehicle3.mph);

  10. println ("Fastest Vehicle : " + fastestVehicle.mph + " mph");



  11. }

  12. }

  13. }


When the previous code is compiled and executed, it produces the following result:



scalac vehicle.scala
scala Vehicle



speed of Bike : 200 mph


speed of Car : 100 mph


speed of Batmobile : 300 mph


Fastest Vehicle : 300 mph


Summary


This appendix introduced you to the basics of Scala. You learned three ways to interactively
execute Scala code as a script and as a compiled program. Then you learned how to use the Scala
collections library. Finally, you learned how to use traits and how to use a singleton object in an
application.

Free download pdf