Class constructor / setter

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) // -10
        b.x = -10
        println(b.x) // 10
    }
}

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?

+3
source share
1 answer

In Scala, the entire class of the class is the main constructor. So you can just do this:

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)
  }
}

Now try:

scala> new SetterTest(-9).x
res14: Int = 9
+6
source

Source: https://habr.com/ru/post/1770869/


All Articles