Scala Primary Constructors

Similar to Java, unless given otherwise each class will have a default constructor. This means that code placed inside the body of the class will be executed per instance.

package scala2

object Tutorial extends App {
  println("Start")
  val t = new StringHolder()
  println("End")
}

class StringHolder {
  println("Creating object instance")
}

This outputs the following:

Start
Creating object instance
End

We can provide a different constructor – the primary constructor – by putting this inline with the class definition as shown:

package scala2

object Tutorial extends App {
  println("Start")
  val t = new StringHolder("This is a test")
  println("End")
}

class StringHolder(text: String) {
  println("Holding string of " + text.length() + " chars")
}

Outputs

Start
Holding string of 14 chars
End

Default values
Like some other languages we can supply a default value for a parameter in the constructor:

package scala2

object Tutorial extends App {
  println("Start")
  val t = new StringHolder()
  println("End")
}

class StringHolder(text: String = "lorem ipsum") {
  println("Holding string of " + text.length() + " chars")
}

Outputting

Start
Holding string of 11 chars
End
Advertisements