0

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?

user79074
  • 4,937
  • 5
  • 29
  • 57

1 Answers1

1

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)
}
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • Neither approach compiles from me in Scala 2.12. When I try to assign I just get a "reassignment to val" error – user79074 Dec 12 '22 at 12:25
  • @user79074 It compiles in Scala 3.2.0 https://scastie.scala-lang.org/DmytroMitin/dWCITqq7TDO9jbOX2JOXNA/1 https://scastie.scala-lang.org/DmytroMitin/dWCITqq7TDO9jbOX2JOXNA/2 and in 2.13.10 https://scastie.scala-lang.org/DmytroMitin/dWCITqq7TDO9jbOX2JOXNA/4 https://scastie.scala-lang.org/DmytroMitin/dWCITqq7TDO9jbOX2JOXNA/3 You're right, it doesn't compile in 2.12.17 https://scastie.scala-lang.org/DmytroMitin/dWCITqq7TDO9jbOX2JOXNA/5 https://scastie.scala-lang.org/DmytroMitin/dWCITqq7TDO9jbOX2JOXNA/6 – Dmytro Mitin Dec 12 '22 at 14:42
  • @user79074 Hmm, I can't reproduce the scala-swing `TextField` behavior in 2.12 at Scastie https://scastie.scala-lang.org/DmytroMitin/dWCITqq7TDO9jbOX2JOXNA/10 Something because of Java 17. Will try to reproduce locally. – Dmytro Mitin Dec 12 '22 at 15:04
  • @user79074 In Scala 2.12 you have to declare both "setter" and "getter". See the update. – Dmytro Mitin Dec 12 '22 at 15:23