且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

标识符中下划线的 Scala 风格指南

更新时间:2021-11-15 23:38:35

尾随下划线是个坏主意,因为像 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 }.我的建议是不要这样做.你要求混淆.使用 myXtheXxLocalxi 或其他东西作为您的内部变量.尽管如此,如果你确实使用_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.