rdoubleui
rdoubleui

Reputation: 3598

Class Constructor/Setter

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?

Upvotes: 3

Views: 1282

Answers (1)

Tom Crockett
Tom Crockett

Reputation: 31579

In Scala, the entire class body makes up the primary constructor. So you can simply 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 to try it:

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

Upvotes: 6

Related Questions