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:
-
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 tox.foo = x.foo + "/something"
. This translation would be less reliable/consistent if it were possible to have a setter without a getter -
Principle of least surprise. I think it’d feel odd if you could invoke
x.foo = bar
but notx.foo == bar
, for instance. Creating both a setter and a getter is howvar
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.
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.