Home »
Scala
Getters and Setters in Scala
By IncludeHelp Last updated : October 22, 2024
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,
Scala 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: Int = 15
def getAverage(): Int = {
Average
}
}
object MyObject {
def main(args: Array[String]): Unit = {
val 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
Scala 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): Unit = {
Average = x
}
def getAverage(): Int = {
return Average
}
}
object MyObject {
def main(args: Array[String]): Unit = {
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