Scala – This Keyword

In Scala, this keyword is used to refer as current object of the class. By using dot(.) after it, we can call instance variable, methods and constructors. As we have seen in earlier post, this is also used with auxiliary constructor.

Let’s understand this keyword with some examples.

Outclass thisExample {

  var name:String=""
  var age:Int=0

  //Auxiliary Constructor
  def this(name:String,age:Int){
    this()                 //Calling Primary constructor
    this.name=name        //Instant Variables
    this.age=age
  }

  def info(): Unit ={
    println("Name: "+name,"Age: "+age)
  }

}

object thisObject{
  def main (args: Array[String] ): Unit = {
  var eg = new thisExample("Roy",25)
    eg.info()
}
}

Output : (Name: Roy,Age: 25)

In the above example, this keyword is used to refer instant variables like name, age and called the constructor. The point to remember here is that calling to other constructor should be the first statement, otherwise it will throw compile time error.

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...