问题描述
我已经从许多其他语言中接受了下划线与标识符中的字母一样的自由度.因此_v
和v_
.此外,建议使用尾随下划线以避免与保留关键字(class_
、case_
)产生歧义.
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
下划线是 Scala 类型系统的重要组成部分,推荐的在标识符中使用它们的方式是什么,以便解析器和人类都能满意?带下划线的标识符会带来哪些可能的歧义?
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?
前导空格似乎会增加混乱 _class
而不是 class_
.
Leading whitespaces seem to add to confusion _class
instead of class_
.
相关问题:
推荐答案
尾随下划线是个坏主意,因为像 x_+
这样的东西本身就是有效的变量名.完全不要使用尾随下划线.
Trailing underscores are a bad idea because things like x_+
are valid variable names on their own. Don't use trailing underscores at all.
前导下划线不是一个坏主意,但仍然很难直观地解析像 _myfunc _
这样的东西.有一些约定使持有同名构造函数参数的私有成员以 _
开头: class X(x: Int) { private var _x = x }
.我的建议是不要这样做.你要求混淆.使用 myX
或 theX
或 xLocal
或 xi
或其他东西作为您的内部变量.尽管如此,如果你确实使用_x
,你会有很好的陪伴;人们往往会明白你的意思.
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.
名称中的下划线没有被广泛使用,因为驼峰式大小写是标准的.我做的一个例外是我在不希望手动使用的隐式 defs 中使用下划线,而是说明发生转换的原因:tuple2_can_expand
可能会添加一个 expand例如,将
Tuple2
转换为 Tuple3
的 code> 方法.
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.
这篇关于标识符中下划线的 Scala 风格指南的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!