10

I have accepted from many other languages that underscores have as much freedom as alphabets in an identifier. Hence _v and v_. Also that trailing underscores are recommended to avoid ambiguity with reserved keywords (class_, case_).

val abc_=0
<console>:1: error: '=' expected but integer literal found.
       val abc_=0

Underscores being an important part of Scala typing system, what is the recommended way to use them in identifiers, so that parser and human can both be happy? What are all possible ambiguities that identifiers with underscores bring?

Leading whitespaces seem to add to confusion _class instead of class_.


Related questions:

Community
  • 1
  • 1
Jesvin Jose
  • 22,498
  • 32
  • 109
  • 202
  • 2
    Check out the [style guide](http://docs.scala-lang.org/style/naming-conventions.html). – agilesteel Mar 11 '12 at 15:39
  • 4
    I've never seen the `class_` thing. I usually see creative misspelling (e.g. `clazz`), or, Scala lets you use keywords as identifiers if you surround them with backticks. – Seth Tisue Mar 11 '12 at 15:55
  • @SethTisue, I got it from Python's PEP8 style guide. My bad; thinking it was a standard. – Jesvin Jose Mar 13 '12 at 05:58

2 Answers2

16

Trailing underscores are a bad idea because things like x_+ are valid variable names on their own. Don't use trailing underscores at all.

Leading underscores are less bad of an idea, but it's still hard to visually parse things like _myfunc _. There is something of a convention to make private members that hold constructor arguments of the same name start with _: class X(x: Int) { private var _x = x }. My recommendation is don't do it. You're asking for confusion. Use myX or theX or xLocal or xi or something for your internal variable. Still, if you do go with _x, you'll have good company; people will tend to know what you mean.

Underscores within a name are not widely used, since camel case is the standard. The exception that I make is that I use underscores within implicit defs that are not expected to be used by hand, and instead state why the conversion is taking place: tuple2_can_expand might add an expand method to convert a Tuple2 into a Tuple3, for example.

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
6

There is only one place you need underscores in identifiers: between alphanumeric characters and other. In fact, that's just what happens in your case: the parser thinks you are declaring val abc_= and don't have = after it! Most common use is for "setter" methods:

def prop: String // or some other type
def prop_=(v: String)

I've also seen predicate_? instead of more Java-like isPredicate.

keyword_ aren't often used, but if you do use them, don't skimp on the whitespace. Write, e.g., val abc_ = 0. But for that matter, val abc = 0 is more readable than val abc=0 as well, so you should have whitespace there anyway. As Rex Kerr says, _privateVariable is acceptable, but not recommended practice.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487