Explain the concept of 'Primary Constructor' in Scala.

Instruction: Describe the role and usage of primary constructors in Scala classes.

Context: This question assesses the candidate's understanding of Scala's class constructors, specifically the primary constructor, its definition within the class declaration, and how it differs from auxiliary constructors.

Updated

A Scala class's primary constructor is expressed by the class declaration and its parameter lists. Construction evaluates the eager initialization expressions in the class body; declaring a method does not execute that method's body, and a lazy value is evaluated when first accessed.

class User(val name: String, initialAge: Int) {
  require(name.nonEmpty, "name must be nonempty")
  require(initialAge >= 0, "age must be nonnegative")
  val age: Int = initialAge
  def this(name: String) = this(name, 0)
  def greeting: String = s"Hello, $name"
}
@main def constructorExample(): Unit = {
  val explicit = new User("Ada", 30)
  val defaulted = new User("Lin")
  assert(explicit.name == "Ada" && explicit.age == 30)
  assert(defaulted.age == 0 && defaulted.greeting == "Hello, Lin")
}

val name exposes a read-only accessor; var would expose a reassignable property. A parameter without val or var, such as initialAge, is not automatically a public field. Case-class parameters have additional generated behavior. Classes and constructor parameters

An auxiliary constructor is a def this that first delegates to another constructor of the same class, eventually reaching the primary constructor. It provides an alternative construction path; default arguments can be simpler for optional inputs. Avoid initialization that calls overridable members before a subclass has initialized its state. Validate actual input requirements separately: this example assumes a non-null name and does not claim comprehensive identity validation.

Related Questions