Accessor和mutator方法是具有特殊名称的常规方法.请看以下示例:
class A {
var x: Int = _
}
Run Code Online (Sandbox Code Playgroud)
与(在"编译器生成以下内容"中)相同:
class A {
private[this] var internal: Int = _
// this is the accessor
def x: Int = internal
// this is the mutator
def x_=(x: Int): Unit = internal = x
}
Run Code Online (Sandbox Code Playgroud)
当您写或读时x,会发生以下情况:
val a: A = ???
println(a.x) // -> method x on A is called
a.x = 1 // syntactic sugar for a.x_=(1)
Run Code Online (Sandbox Code Playgroud)
关于这一点的好处是,您可以var在以后更改a 以包括一致性检查:
class A {
private[this] var _x: Int = _
def x: Int = _x
def x_=(x: Int): Unit = {
if (x < 0)
throw new IllegalArgumentException("Must be non-negative")
_x = x
}
}
Run Code Online (Sandbox Code Playgroud)
透明地通过访问器/变换器替换变量的能力也称为统一访问原则.
| 归档时间: |
|
| 查看次数: |
1797 次 |
| 最近记录: |