1.

What Is Primary Constructor? What Is Secondary Or Auxiliary Constructor In Scala? What Is The Purpose Of Auxiliary Constructor In Scala? Is It Possible To Overload Constructors In Scala?

Answer»

Scala has two kinds of constructors:

  • Primary Constructor
  • Auxiliary Constructor

Primary Constructor: In Scala, Primary Constructor is a constructor which is defined with class definition itself. Each class must have one Primary Constructor: Either PARAMETER constructor or Parameterless constructor.

Example:-

class Person

Above Person class has one Zero-parameter or No-Parameter or Parameterless Primary constructor to create instances of this class.

class Person (firstName: STRING, lastName: String)

Above Person class has a two PARAMETERS Primary constructor to create instances of this class.

Auxiliary Constructor: Auxiliary Constructor is also known as Secondary Constructor. We can declare a Secondary Constructor USING ‘def’ and ‘this’ keywords as shown below:

class Person (firstName: String, middleName:String, lastName: String){
def this(firstName: String, lastName: String){
this(firstName, "", lastName)
}
}

Scala has two kinds of constructors:

Primary Constructor: In Scala, Primary Constructor is a constructor which is defined with class definition itself. Each class must have one Primary Constructor: Either Parameter constructor or Parameterless constructor.

Example:-

class Person

Above Person class has one Zero-parameter or No-Parameter or Parameterless Primary constructor to create instances of this class.

class Person (firstName: String, lastName: String)

Above Person class has a two Parameters Primary constructor to create instances of this class.

Auxiliary Constructor: Auxiliary Constructor is also known as Secondary Constructor. We can declare a Secondary Constructor using ‘def’ and ‘this’ keywords as shown below:

class Person (firstName: String, middleName:String, lastName: String){
def this(firstName: String, lastName: String){
this(firstName, "", lastName)
}
}



Discussion

No Comment Found