Search code examples
scalagetter-settermagic-methodssyntactic-sugar

Underscore usage in Scala's identifier


I have a class with getter/setter:

class Person {
    private var _age = 0

    //getter
    def age = _age

    //setter
    def age_=(value: Int): Unit = _age = value
}

We know that we can invoke setter method like this:

val p = new Person()
p.age= (2)
p age= 11
p.age= 8-4

What made interesthing in this case is: the underscore (_) in def age_= can be removed when the method is invoked.

My question is what is the underscore used for in this case?

Someone told me it is used to separate non-alphanum character in identifier. So I tried this:

var x_= = 20
x_= = 10
x= = 5    // I got error here

Why I can't remove the underscore in this case?

Also, if I tried to use the underscore more than once:

val x_=_x = 1

I got compile error too.

Is there a rule about the underscore usage and what is the term for this underscore usage?


Solution

  • The compile error says it all, really:

    scala> var x_= = 20
    <console>:10: error: Names of vals or vars may not end in `_='
    

    Only methods are allowed to have names ending in _=. This makes sense, because it would be really confusing to allow a val to be named x_=

    However it is true that the underscore is used to separate alpha-numeric characters from special characters. It's just that in the case of a val or var, you can't end it with =

    scala> var x_# = 20
    x_#: Int = 20
    scala> x_# = 10
    x_$hash: Int = 10
    

    I don't think another underscore is allowed after the first underscore that precedes special characters.

    val x_y_^ = 1    // Ok
    val x_^_^ = 1    // Not ok
    

    Based on the Scala language spec :

    First, an identifier can start with a letter which can be followed by an arbitrary sequence of letters and digits. This may be followed by underscore ‘’ characters and another string composed of either letters and digits or of operator characters.

    See also Example 1.1.1 in the linked specification for examples of valid identifiers.