I'm currently learning Scala, and just discovered the way to create custom field getters/setters. I have a simple example working:
class Thing(private val a:Int){ override def toString = "Thing[" + a + "]" private var _value = a def value = _value def value_= (newVal:Int) = _value = newVal } On the console I can do:
scala> var t = new Thing(2) t: dylan.code.Thing = Thing[2] scala> t.value res1: Int = 2 scala> t.value = 3 scala> t.value res2: Int = 3 Now I'm trying to bring this concept to a slightly more complicated example; I'll try to whittle the code down to what's relevant:
abstract class CellExpression[Type] extends Publisher[CellUpdateEvent[Type]] with Subscriber[CellUpdateEvent[Type], CellExpression[Type]]{ protected var cachedValue: Type = recalculateValue() protected def recalculateValue(): Type protected def changeValue(newValue: Type):Unit = { val oldValue = value() if(newValue != oldValue){ cachedValue = newValue publish(new CellUpdateEvent(this, oldValue, newValue)) } } def value() = cachedValue def notify(pub: CellExpression[Type], event: CellUpdateEvent[Type]) = changeValue(recalculateValue()) } //.... class CellVariable[Type](private val initialValue:Type) extends CellExpression[Type]{ cachedValue = initialValue protected def recalculateValue() = { cachedValue } override def toString = "CellVariable[" + value + "]" def value_= (newValue:Type) = {changeValue(newValue)} } As far as I can tell, I've done what I need to in order to be able to treate value as a field via its getter and setter. But when I try it out in the console, I get:
scala> var i = new CellVariable(2) i: dylan.code.CellVariable[Int] = CellVariable[2] scala> i.value = 3 <console>:11: error: reassignment to val i.value = 3 ^ What have I done wrong, and how can I fix it?