Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala style guideline for underscore in identifiers

Tags:

scala

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:

  • What are all the uses of an underscore in Scala?
  • Scala underscores in names
like image 476
Jesvin Jose Avatar asked Mar 11 '12 15:03

Jesvin Jose


1 Answers

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.

like image 117
Rex Kerr Avatar answered Oct 21 '22 04:10

Rex Kerr