Try to imagine how much code it would take to generate the following in your favorite language:

  class Car( model: String, year: Int = 2017){
    def description = s"The $year $model has arrived"
}

So, in this small class here are the hidden goodies the developer gets for free:

  • In Scala the parameter list to a class does a bunch of work. There is a lot about this we can go into but I will likely do another post about it. For now suffice it to say the PRIMARY CONSTRUCTOR generates useful bits for you.

  • Fields can be used in the class equivalent to private[this] val.

  • The way the params are defined without the var or the val makes the fields object private

  • For regular method parameters use val or var designations. For val the reader methods will be generated behind the scenes. For var the reader and writer methods will be spun up.

  • Without additional work you can use the params in methods of the class. This tightens up the code.

//Model can change but year is set.
  class Car( var model: String, val year: Int = 2017){
    def description = s"The $year $model has arrived"
}
  • The model and year variables are initialized and become fields on Car.