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.
Scala中的Getter和Setter是用于访问和实例化Scala中类或特征变量的方法。 这些方法具有与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
翻译自: https://www.includehelp.com/scala/getters-and-setters.aspx