I know that in Scala I can write getters/setters like this:
class Person() {
// Private age variable, renamed to _age
private var _age = 0
var name = ""
// Getter
def age = _age
// Setter
def age_= (value:Int):Unit = _age = value
}
Where the _
in def age_=
represents a whitespace. (Source)
Following this principle, I would like to write something like this:
object SubjectUnderObs {
var x: Int = 0
private var myListeners : Set[Int => Unit] = Set()
def listeners_+= (listener: Int => Unit): Unit =
myListeners = myListeners + listener
}
// This does not compile
SubjectUnderObs.listeners += { newX =>
println(newX)
}
I basically want to add callbacks using this kind of syntax: SubjectUnderObs.listeners +=
. In my case however, I cannot omit the _
. Why doesn't this work the same way as the setter above and how can I achieve what I want?