Scala 在名称中下划线 [英] Scala underscores in names
问题描述
我阅读了多个样式指南和其他资源,指出在方法/变量/其他名称中使用下划线是个坏主意.
I've read multiple style guidelines and other resources stating it's a bad idea to use underscores in method/variable/other names.
这背后的技术原因是什么?
What are the technical reasons behind this?
我很习惯例如用 _ 预先添加辅助函数.还有一些我想公开的应该是私有的函数,以便我可以通过 REPL 访问它们.使用helper"后缀等其他命名约定似乎很麻烦.
I'm very accustomed to e.g. prepending helper functions with _. There are also functions that should be private that I want to make public so I can access them via the REPL. Other naming conventions like using a "helper" suffix just seem cumbersome.
任何想法将不胜感激!
推荐答案
通配符 _
在 Scala 中被大量使用.所以:
The wildcard operator _
is used heavily in Scala. So:
xs map (_.x) // Call the x method of every element
xs map (_x) // Pass every element through the _x method
令人困惑.您必须非常仔细地查看下划线是否在前面.
is confusing. You have to look very carefully to see if the underscore is prepended.
但是,内部下划线更难混淆:
However, internal underscores are harder to confuse:
xs map (my_method) // No similar form where _ stands for the list element
所以这些问题不那么严重,但是当人们在寻找闭包时,下划线仍然有点吸引眼球.这可能是他们不鼓励使用它们的原因,但说实话,我一直在使用它们,特别是在隐式 defs 和内部变量之类的东西中,它们在界面中不会有太多或任何暴露.
So these are less problematic, but the underscores still catch the eye a little when one is looking for closures. This is probably why they're discouraged, but to be honest, I use them all the time, particularly in things like implicit defs and internal variables where they won't have much or any exposure in an interface.
这篇关于Scala 在名称中下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!