Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Constructor/Setter

Tags:

scala

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?

like image 206
rdoubleui Avatar asked Dec 29 '25 11:12

rdoubleui


1 Answers

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
like image 101
Tom Crockett Avatar answered Jan 01 '26 19:01

Tom Crockett