Scala – Auxiliary Constructor

  • date 22nd April, 2021 |
  • by Prwatech |
  • 0 Comments

In Scala Program, the constructors other than the primary constructor are called as Auxiliary Constructors. We can create any number of auxiliary constructors in our Scala class, but scala class has only one primary constructor.
Auxiliary constructors are mentioned as methods in the class by using this keyword.

use case 1:

scala> class student{

     var roll = 2

     var age = 4

     def this(roll: Int){

     this() //call the primary constructor

     this.roll = roll

     }

     def this(roll:Int, age:Int)

     {

     this(roll) //calls previous auxiliary constructor

     this.age = age

     }

     }

       def this(roll: Int){

class student

scala> var mark = new student(123,18)

scala> var frank = new student(137,18)

scala> var sam = new student(167,18)

scala> println(mark.roll,mark.age)

scala> println(frank.roll,frank.age)

scala> println(sam.roll,sam.age)

use case 2:

class prwatech{

      var size =0;

      var age = 0;

            def this(size: Int){

            this() //call the primary constructor

           this.size = size

           }

           def this(size:Int, age:Int)

           {

               this(size) //calls previous auxiliary constructor

                this.age = age

            }

          }

scala> var a = new prwatech(1,2)

scala> var b = new prwatech(3,5)

scala> var c = new prwatech(4,1)

scala> println(a.size,a.age)

scala> println(b.size,b.age)

scala> println(c.size,c.age)

use case 3:

scala> class prwatech{

     var size =1;

     var age = 2;

     def this(size: Int){

     this() //call the primary constructor

     this.size = size

     }

     def this(size:Int, age:Int)

     {

     this(size) //calls previous auxiliary constructor

     this.age = age

     }

     }

scala> var a = new prwatech(3,0)

scala> var b = new prwatech(0,0)

scala> var c = new prwatech(0,7)

scala> println(a.size,a.age)

scala> println(b.size,b.age)

scala> println(c.size,c.age)

0
0

Quick Support

image image