Hi,
I'm fairly new to Scala, coming from a basic Java background. I looked at how to implement class constructors and how to provide some logic in the setter for a field of that 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
, therefore the setter is not used. What if I want to use the logic of the setter?
object Test {
def main(args: Array[String]) {
val b = new SetterTest(-10)
println(b.x) // -10
b.x = -10
println(b.x) // 10
}
}
In Java I could have used the setter in the constructor to force using this sample piece of logic.
How would I achieve this in scala?