How is the property assignment in scala swing implemented

49 Views Asked by At

In scala swing I can do something like the following:

val field = new TextField("", 4)
field.text = "Hello"

And the assignment is implemented thus:

  def text_=(t: String): Unit = peer.setText(t)

But if I try my own implementation such as:

  case class A(i: Int) {
    def value_=(j: Int) = copy(i = j)
  }
  
  val a = A(3)
  a.value = 3

This will not compile for me. What am I missing?

1

There are 1 best solutions below

4
On

In Scala 2.13 (and 3) the setter def value_= (or def value_$eq) seems to work if you declare a field value

case class A(i: Int) {
  val value: Int = 0
  def value_=(j: Int) = copy(i = j)
}

or

case class A(i: Int, value: Int = 0) {
  def value_=(j: Int) = copy(i = j)
}

By the way, it's a little confusing that a setter value_= returns A rather than Unit

println(a.value = 4) // A(4,0)

In Scala 2.12 the "setter" def value_= (or def value_$eq) works if you declare a "getter" too

case class A(i: Int) {
  def value = "value"
  def value_=(j: Int) = copy(i = j)
}