I am new to Scala, based on the underlying Java background. I looked at how to implement class constructors and how to provide some logic in the installer for the field of this class.
class SetterTest(private var _x: Int) {
def x: Int = _x
def x_=(x: Int) {
if (x < 0) this._x = x * (-1)
}
}
The constructor parameter is assigned to the field _x, so the installer is not used. What if I want to use setter logic?
object Test {
def main(args: Array[String]) {
val b = new SetterTest(-10)
println(b.x)
b.x = -10
println(b.x)
}
}
In Java, I could use the installer in the constructor to force the use of this sample logic.
How do I achieve this in scala?
source
share