Scala - This Keyword



This chapter takes you through usage of the "this" keyword in Scala programming. The "this" keyword in Scala is used to reference the current instance of a class. The "this" keyword has various important purposes. For example, disambiguating between class fields and parameters, invoking other constructors, and passing the current instance as a parameter.

This Keyword

The "this" keyword refers to the current instance of a class. You can access members (fields and methods) of the current object within its scope. In Scala, this is used to differentiate between class fields and method parameters with the same name. It can also be used to call another constructor of the same class (this constructor). So, you can reuse of initialization logic across multiple constructors.

Syntax

This is simple syntax of this keyword used in Scala programming -

class ClassName(parameter1: Type, parameter2: Type) {
  def method(): Unit = {
    println(this.parameter1)
  }

  def this(parameter1: Type) {
    this(parameter1, defaultValue)
    // Additional initialization
  }
}

Here, a class is defined with various parameters and methods. The use of this keyword inside the method of this class, so it will refer to the current instance. There is also this keyword in the auxiliary constructor (this(parameter1, defaultValue)). It calls the primary constructor with parameters. So, you can have various ways to initialize instances of the class.

These are various uses of the "this" keyword in Scala programming. We have explained some of the following.

1. Using this to Reference Class Fields

The "this" keyword can be used to reference class fields, especially when constructor parameters have the same names as class fields.

Example

The following example shows the use of the "this" keyword to differentiate between class fields and constructor parameters.

class Employee(name: String, age: Int) {
  private var empName: String = this.name
  private var empAge: Int = this.age

  def displayInfo(): Unit = {
    println(s"Employee Name: $empName, Age: $empAge")
  }
}

object Demo {
  def main(args: Array[String]): Unit = {
    val employee = new Employee("Alice", 30)
    employee.displayInfo()
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Employee Name: Alice, Age: 30

In the example, the Employee class uses the "this" keyword to refer to the class fields empName and empAge. These are initialized with the constructor parameters name and age.

2. Using this to Invoke Auxiliary Constructors

The "this" keyword is used to invoke auxiliary constructors within the same class. Auxiliary constructors provide alternative ways to create instances of a class.

Example

The following example shows how to use the "this" keyword to invoke an auxiliary constructor.

class Rectangle(val width: Int, val height: Int) {
  var area: Int = width * height

  // Auxiliary constructor
  def this(side: Int) = {
    this(side, side)
  }

  override def toString: String = s"Rectangle(width: $width, height: $height, area: $area)"
}

object Demo {
  def main(args: Array[String]): Unit = {
    val rectangle1 = new Rectangle(10, 20)
    val rectangle2 = new Rectangle(15)
    println(rectangle1)
    println(rectangle2)
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Rectangle(width: 10, height: 20, area: 200)
Rectangle(width: 15, height: 15, area: 225)

In the example, the Rectangle class has a primary constructor and an auxiliary constructor. The auxiliary constructor uses the "this" keyword to call the primary constructor. So, you can create a square with only one side length.

3. Passing this as a Parameter

The "this" keyword can be used to pass the current instance of a class as a parameter to other methods or constructors.

Example

The following example shows how to pass this as a parameter to another method.

class Person(val name: String) {
  def greet(person: Person): Unit = {
    println(s"Hello, ${person.name}! My name is ${this.name}.")
  }
}

object Demo {
  def main(args: Array[String]): Unit = {
    val alice = new Person("Alice")
    val bob = new Person("Bob")
    alice.greet(bob)
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Hello, Bob! My name is Alice.

In the example, the Person class has a greet method that takes another Person object as a parameter. The "this" keyword is used to reference the current instance. So one person to greet another.

Scala this Keyword Summary

  • The "this" keyword in Scala refers to the current instance of a class.
  • It is used to access class fields and methods, invoke auxiliary constructors, and pass the current instance as a parameter.
  • You can disambiguate between class fields and constructor parameters with the same names.
Advertisements