Sunday, 4 January 2015

Class Constructor in Scala

1. visibility of constructor fields
  • If a field is declared as a var, Scala generates both getter and setter methods for that field.
  • If the field is a val, Scala generates only a getter method for it.
  • If a field doesn’t have a var or val modifier, Scala gets conservative, and doesn’t generate a getter or setter method for the field.
  • Additionally, var and val fields can be modified with the private keyword, which prevents getters and setters from being generated.
  • Case class constructor parameters are val by default. 
2. The primary constructor of a Scala class is a combination of:
  • The constructor parameters
  • Methods that are called in the body of the class
  • Statements and expressions that are executed in the body of the class
Anything defined within the body of the class other than method declarations is a part of the primary class constructor.

3. Define one or more auxiliary constructors for a class to give consumers of the class different ways to create object instances.

  • Auxiliary constructors are defined by creating methods named this.
  • Each auxiliary constructor must begin with a call to a previously defined constructor.
  • Each constructor must have a different signature.
  • One constructor calls another constructor with the name this.

No comments:

Post a Comment