tags:

views:

85

answers:

1

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?

+5  A: 

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
pelotom
@pelotom: Yes, that's one of Scala's sore points. You can have either the short succinct code without setters or some Java-like bloat with setters. The problem is that the compiler doesn't recognize it if you define the setters/getters yourself and will fail with some non-helpful error message. Additionally setting members of a class via the constructor circumvents any defined setter method, violating the unified access principle. This is one of Scala's dark spots...
soc
@ pelotom: Thanks for a quick solution. @soc +1 for bringing in further thoughts to help me evaluate what I'm learning.
rdoubleui