[SOLVED] Why does `*_=(..)` only work with setter AND getter?

Is there a specific reason why the def foo_=(newValue: String): Unit = ??? construct only works if there is as well a method with the name def foo: String = ???

This behavior is part of the language spec. While I’m unaware of a documented reason it’s in the spec at all I can think of two potential justifications:

  1. Playing nicely with the compound operator translation. Syntax like x.foo += "/something" becomes automatically available when both a setter and getter are present because it will get translated to x.foo = x.foo + "/something". This translation would be less reliable/consistent if it were possible to have a setter without a getter

  2. Principle of least surprise. I think it’d feel odd if you could invoke x.foo = bar but not x.foo == bar, for instance. Creating both a setter and a getter is how var works and how standard imperative variables work, so it’s consistent there too. In a sense, what use is a setter without a getter? I struggle to think of a use case where there’s value for the user to be able to set something arbitrarily but never retrieve the current state.

2 Likes

Thank you for putting in your thoughts about that. The issue turned up in my implementation when I had a state that could be set from outside but should not be readable from outside a class.