Hello fellow Scalaists,
I recently took another look at setters in Scala and found out that _ in a method name seems to translate to "There might be a space or not and oh also treat the next special character as part of the method name".
Secondly, can someone please explain why the second to last line doesnt work?
class Person() {
private var _name: String = "Hans"
def name = _name
def name_=(aName: String) = _name = aName.toUpperCase
}
val myP = new Person()
myP.name = "test"
myP.name= "test"
myP.name_= "test" //Bad doesnt work
myP.name_=("test")//Now It works
Lastly, removing the getter breaks the above example
class Person() {
private var _name: String = "Hans"
def name_=(aName: String) = _name = aName.toUpperCase
}
val myP = new Person()
myP.name = "test" //Doesnt work anymore
myP.name= "test" //Doesnt work anymore
myP.name_= "test" //Still doesnt work
myP.name_=("test")//Still works
Edit: Here is a quote(seemingly false) from the source which I originally read, and which spawned this question:
This line is a bit more tricky but I'll explain. First, the method name is "age_=". The underscore is a special character in Scala and in this case, allows for a space in the method name which essentially makes the name "age ="
http://dustinmartin.net/getters-and-setters-in-scala/
So first of all, is this correct?
No, underscores in method names do not work exactly like what you described. It doesn't mean "there might be a space and the character after the space is also part of the method name".
Section 4.2 of the Scala Language Specification explains what a method that has a name that ends with _=
means.
A variable declaration
var x: T
is equivalent to the declarations of both a getter functionx
and a setter functionx_=
:def x: T def x_= (y: T): Unit
An implementation of a class may define a declared variable using a variable definition, or by defining the corresponding setter and getter methods.
Note that if you only define the setter method and not the getter method, then the magic of the setter method disappears - it's treated as just another method that has a name that happens to end with _=
, but this has no special meaning in this case.
Only if there are a getter and setter, the method with _=
acts as the setter and can be used as such - that's why myP.name = "test"
doesn't work anymore if you remove the getter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With