应该避免 x._1,x._2... 语法吗? [英] Should x._1,x._2... syntax be avoided?
问题描述
我刚开始接触 Scala.我发现自己经常使用元组变量.
I'm just starting out in Scala. I find myself using tuple variables a lot.
例如,这是我写的一些代码:
For example, here's some code I wrote:
/* Count each letter of a string and return in a list sorted by character
* countLetter("test") = List(('e',1),('s',1),('t',2))
*/
def countLetters(s: String): List[(Char, Int)] = {
val charsListMap = s.toList.groupBy((c:Char) => c)
charsListMap.map(x => (x._1, x._2.length)).toList.sortBy(_._1)
}
Scala 开发人员不喜欢这种元组语法(x._1、x._2 等)吗?
Is this tuple syntax (x._1, x._2 etc) frowned upon by Scala developers?
推荐答案
Scala 开发人员是否不喜欢元组访问器?
Are the tuple accessors frowned upon by Scala developers?
简答:没有.
稍长(一个字符)答案:是的.
Slightly longer (by one character) answer: yes.
过多的 _n
可能是代码异味,在我看来,以下情况更清晰:
Too many _n
's can be a code smell, and in your case the following is much clearer, in my opinion:
def countLetters(s: String): List[(Char, Int)] =
s.groupBy(identity).mapValues(_.length).toList.sortBy(_._1)
有很多像 mapValues
这样的方法专门设计用于减少对嘈杂的元组访问器的需求,所以如果你发现自己在编写 _1
等,,很多,这可能意味着您缺少一些不错的库方法.但有时它们是最干净的写东西的方式(例如,我重写中的最终 _1
).
There are lots of methods like mapValues
that are specifically designed to cut down on the need for the noisy tuple accessors, so if you find yourself writing _1
, etc., a lot, that probably means you're missing some nice library methods. But occasionally they're the cleanest way to write something (e.g., the final _1
in my rewrite).
另一件需要注意的事情是,过度使用元组访问器应该被视为将元组提升为案例类的推动力.考虑以下几点:
One other thing to note is that excessive use of tuple accessors should be treated as a nudge toward promoting your tuples to case classes. Consider the following:
val name = ("Travis", "Brown")
println("Hello, " + name._1)
相反:
case class Name(first: String, last: String)
val name = Name("Travis", "Brown")
println("Hello, " + name.first)
第二个版本中额外的案例类定义为一行代码带来了很多可读性.
The extra case class definition in the second version buys a lot of readability for a single line of code.
这篇关于应该避免 x._1,x._2... 语法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!