Home » Scala language

this keyword in Scala

Scala this keyword: this keyword is used to fetch the variable of the current class. In this tutorial, we will learn about this keyword in Scala, it's working and sample codes.
Submitted by Shivang Yadav, on September 09, 2019

Scala 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,

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 students 
{ 
	var name: String = ""
	var marks = 0
	
	def info(name:String, marks:Int ) 
	{ 
		this.name = name 
		this.marks = marks 
	} 
	def show() 
	{
		println("Student " + name + " has obtained " + marks + " marks " ) 
	} 
} 

object Myobject 
{ 
	def main(args: Array[String]) 
	{ 
		var s1 = new students() 
		s1.info("Kabir", 473) 
		s1.show()
	} 
} 

Output

Student Kabir has obtained 473 marks 

Explanation:

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 = 0
	
	def this(name:String, marks:Int ) 
	{ 
		this();
		this.name = name 
		this.marks = marks 
	} 
	def show() 
	{
		println("Student " + name + " has obtained " + marks + " marks " ) 
	} 
} 

object Myobject 
{ 
	def main(args: Array[String]) 
	{ 
		var s1 = new students("Kabir", 473) 
		s1.show()
	} 
} 

Output

Student Kabir has obtained 473 marks 


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.