1

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?

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
null
  • 8,669
  • 16
  • 68
  • 98
  • 1
    Take a look at http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala for other usages of underscore in Scala. [This](http://stackoverflow.com/a/19087649/158074) answer also explains how the assignment operator override works. – rsenna Jan 02 '15 at 18:13

1 Answers1

2

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.

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
  • Thanks very much. But what is the explanation of `p.age= 8-4`? It doesn't need to put the underscore. – null Jan 02 '15 at 18:33
  • 1
    It's not that you're dropping the underscore, exactly. The compiler just handles methods that end in `_=` specially. i.e. `p.age = 8-4` is handled like `p.age_=(8-4)`. Notice how you can also put a space there. – Michael Zajac Jan 02 '15 at 18:42
  • So we can say the underscore removing in this case is part of language's syntax? – null Jan 02 '15 at 18:53
  • I see. I hope not many magical pattern would be employed in scala. – null Jan 02 '15 at 19:07