Scala – Auxiliary Constructor

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

Auxiliary Class Constructors Scala Book

 

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)

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

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

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

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

4scala> 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)

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

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

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

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

4scala> 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)

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

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

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

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

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

Auxiliary Class Constructors Scala Book

Quick Support

image image