Scala program to demonstrate the 'this' keyword

Here, we are going to demonstrate the 'this' keyword in Scala programming language.
Submitted by Nidhi, on June 28, 2021 [Last updated : March 11, 2023]

Scala – 'this' Keyword Example

Here, we will create a class with two data members. And, we will also define two methods, there we will use the this keyword to differentiate the member of the class and the parameters of the method. The this keyword is always used to represent the member of the class.

Scala code to demonstrate the example of 'this' keyword

The source code to demonstrate this keyword is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to demonstrate "this" keyword

class Demo {
  var num1: Int = 0;
  var num2: Int = 0;

  def setValues(num1: Int, num2: Int) {
    this.num1 = num1;
    this.num2 = num2;

  def printValues() {
    printf("Num1: %d\n", this.num1);
    printf("Num2: %d\n", this.num2);

object Sample {
  def main(args: Array[String]) {
    // Create an object of Demo class
    var obj = new Demo()
    obj.setValues(100, 200);


Num1: 100
Num2: 200


Here, we used an object-oriented approach to create the program. And, we created an object Sample.

Here, we created a class Demo with two members num1 and num2. The Demo class contain two methods setValues() and printValues(). The name parameters of setValues() method and data members are the same. That's why we used this keyword to differentiate parameters and data members. The this keyword is used with data members of the class.

In the main() function, we created an object of the Demo class and then set and print the value of data members.

Scala Classes & Objects Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.