user8331236
user8331236

Reputation:

How "this" keyword is using and working in Scala Auxiliary Constructor?

I have started learning Scala just now, help me to understand that how the age is printing where student class has two parameters

class Student(id: Int, name: String) {
  var age: Int = 0
  def showDetails() {
    println(id + " " + name + " " + age)
  }
  def this(id: Int, name: String, age: Int) {
    this(id, name)
    this.age = age
  }
}

object hi {
  def main(args: Array[String]) {
    var s = new Student(101, "Sun", 20);
    s.showDetails()
  }
}

Upvotes: 4

Views: 1749

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

that how the age is printing where student class has two parameters

Student has two constructors. An auxilary constructor with two parameters:

class Student(id: Int, name: String)

But it also defines an additional constructor with three parameters via this():

def this(id: Int, name: String, age: Int)

When you create an instance of Student in main, you use the secondary constructor which accepts three arguments:

var s = new Student(101, "Sun", 20);

Thus, 20 is the age. If you'd use the auxiliary constructor, age would still be set to 0 making showDetails() print out 0.

Upvotes: 7

Assaf Mendelson
Assaf Mendelson

Reputation: 13001

When you construct this class with two parameters, then the construction process will first call:

var age: Int = 0

setting the age to 0. so the age of the student would be 0 unless you specifically change it.

When you call with three arguments, this is exactly what you do, you construct setting age to 0 and then change it to the third argument.

P.S. you are defining the id and name implicitly to be a private val. It would be better to do it explicitly.

The reason for this is that if you do:

class A(a: Int) {
}

then a is not part of the object at all, a is just an argument for the constructor.

If However you use a in a method:

class A(a: Int) {
  def b: Int = a
}

Then scala needs to save it for later use (it must be available outside the construction when b is called). It will therefore transform it to a private val.

To avoid confusion, it would be better to do:

class A(private val a: Int) {
  def b: Int = a
} 

Upvotes: 2

Related Questions