Home » Scala language

Getters and Setters in Scala

Getters and Setters are methods to access and manipulate variables in Scala. In this tutorial, we will learn about getters and setters with working examples.
Submitted by Shivang Yadav, on March 06, 2020

Getter and Setters in Scala are methods that are used to access and instantiate a variable of a class or trait in Scala. These methods have similar functioning as in Java.

Let's see the function of each of them in detail,

Getters

Getters are methods that are used to access the value of a variable of a class/trait.

Getting the values of variables is easy and can be done just by calling the name of the variable with the object name.

    object_name.varaible_name 

Variables always have some restrictions on the usage which is done by access specifiers, so we need to call the variables using general public method calls.

    object_name.method()

Example:

class Bike 
{ 
	var Model: String= "Harley Davidson Iron 833"
	var TopSpeed: Int= 183
	private var Average= 15

	def getAverage(): Int ={ 
		return Average 
	} 
} 

object MyObject 
{ 
	def main(args: Array[String]) 
	{ 
		var myBike = new Bike() 
		println("Bike Name: " + myBike.Model) 
		println("Top Speed: " + myBike.TopSpeed) 
		println("Average: " + myBike.getAverage) 
	} 
} 

Output

Bike Name: Harley Davidson Iron 833
Top Speed: 183
Average: 15

Setters

Setters are methods that are used to set the value of a variable of a class/trait.

Setting the values of variables is easy and can be done just by calling the name of the variable with the object name.

    object_name.varaible_name = value

Variable always have some restrictions on the usage which is done by access specifiers, so we need to call the variables using general public method calls.

    object_name.setterMethod()

Example:

class Bike 
{ 
	var Model: String= ""
	var TopSpeed: Int= 0
	private var Average= 0
	
	def setAverage(x : Int){
		Average = x;
	}
	def getAverage(): Int ={ 
		return Average 
	} 
} 

object MyObject 
{ 
	def main(args: Array[String]) 
	{ 
		var myBike = new Bike() 
		myBike.Model = "BMW S1000 RR"
		myBike.TopSpeed = 300
		myBike.setAverage(15) 
		
		println("Bike Name: " + myBike.Model) 
		println("Top Speed: " + myBike.TopSpeed) 
		println("Average: " + myBike.getAverage) 
	} 
} 

Output

Bike Name: BMW S1000 RR
Top Speed: 300
Average: 15


Comments and Discussions!

Load comments ↻





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