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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With