我是Scala的新手,来自基本的Java背景.我研究了如何实现类构造函数以及如何在setter中为该类的字段提供一些逻辑.
class SetterTest(private var _x: Int) {
def x: Int = _x
def x_=(x: Int) {
if (x < 0) this._x = x * (-1)
}
}
Run Code Online (Sandbox Code Playgroud)
构造函数参数已分配给字段_x,因此不使用setter.如果我想使用setter的逻辑怎么办?
object Test {
def main(args: Array[String]) {
val b = new SetterTest(-10)
println(b.x) // -10
b.x = -10
println(b.x) // 10
}
}
Run Code Online (Sandbox Code Playgroud)
在Java中,我可以使用构造函数中的setter来强制使用这个逻辑示例.
我如何在scala中实现这一点?
在Scala中,整个类主体构成了主要的构造函数.所以你可以这样做:
class SetterTest(private var _x: Int) {
x = _x // this will invoke your custom assignment operator during construction
def x: Int = _x
def x_=(x: Int) {
if (x < 0) this._x = x * (-1)
}
}
Run Code Online (Sandbox Code Playgroud)
现在尝试一下:
scala> new SetterTest(-9).x
res14: Int = 9
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1127 次 |
| 最近记录: |