Home »
Scala
this keyword in Scala
By IncludeHelp Last updated : October 22, 2024
'this' keyword
this keyword in Scala is used to refer to the object of the current class. Using this keyword you can access the members of the class like variables, methods, constructors.
In Scala, this keyword can be used in two different ways,
this with Dot (.) Operator
The dot (.) operator in Scala is used to call members of the current class. Both data members and member functions can be called using a dot (.) operator.
Syntax
this.member_name;
this will call members associated with the current object of the class. you can call any member associated using dot (.) operator.
Example
class Student {
var name: String = ""
var marks: Int = 0
def info(name: String, marks: Int): Unit = {
this.name = name
this.marks = marks
}
def show(): Unit = {
println("Student " + name + " has obtained " + marks + " marks.")
}
}
object MyObject {
def main(args: Array[String]): Unit = {
val s1 = new Student()
s1.info("Kabir", 473)
s1.show()
}
}
Output
Student Kabir has obtained 473 marks
The above code is used to display implementation of this keyword with the dot operator. In the program, we have named students which contains some variables. In methods of the student class, we have used with this keyword with the dot operator to call data member of the class.
Using this()
In Scala programming language, constructors can be called using this keyword. this keyword is used to create the auxiliary constructors and Scala. For an auxiliary constructor, the first line in the constructor should be a call to another constructor to run without error.
Syntax
this(){
}
Here, this keyword is used to define a constructor that of the class. The constructor created is an auxiliary constructor that needs to call another auxiliary constructor or primary constructor in its call.
Example
class Students {
var name: String = ""
var marks: Int = 0
def this(name: String, marks: Int) {
this()
this.name = name
this.marks = marks
}
def show(): Unit = {
println("Student " + name + " has obtained " + marks + " marks")
}
}
object MyObject {
def main(args: Array[String]): Unit = {
val s1 = new Students("Kabir", 473)
s1.show()
}
}
Output
Student Kabir has obtained 473 marks
Constructor calling by using this keyword
The "this" keyword is used to call another constructor from within a constructor in Scala. This feature allows constructor overloading.
Example
class Student(name: String) {
def this(name: String, age: Int) {
this(name)
println(s"Student's name is $name and age is $age")
}
}
object MainObject {
def main(args: Array[String]): Unit = {
val s = new Student("Aarav", 22)
}
}
Output
Student's name is Aarav and age is 22