Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore in method names

Tags:

scala

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".

  1. So first of all, is this correct?
  2. 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
    
  3. 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/

like image 890
PhilBa Avatar asked Sep 18 '25 23:09

PhilBa


1 Answers

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 function x and a setter function x_=:

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.

like image 162
Jesper Avatar answered Sep 22 '25 10:09

Jesper