在Scala中,为什么`_`不能在groupBy中使用? [英] In Scala, why `_` can't be used in groupBy here?
问题描述
我试图计算每个字符出现在单词中的列表,我现在的代码如下所示: hello
.groupBy((x:Char)=> x)
.map(a =>(a._1,a._2.length))
我认为 .groupBy((x:Char)=> x)
看起来笨拙,因此重写如下:
hello
.groupBy(_)
.map (a =>(a._1,a._2.length))
但编译器抛出一个错误
$ b $ pre $ 错误:(1,18)缺少扩展函数的参数类型((x $ 1)=>hello .groupBy(x $ 1).map(((a)=> scala.Tuple2(a._1,a._2.length))))
hello.groupBy(_)。map(a =>(a._1,a._2.length))
^
有人对此有何看法?或者有没有更好的方法来写这个?
x.groupBy(_)
,就像任何方法 x.foo(_)
一样,意味着将此方法转换为函数,即 y => x.groupBy(y)
。
因为 _
它也可以表示在这里插入值。然而,由于上面的含义,插入身份不起作用。
您可以执行 x => x
或 identity
来获得您想要的 _
。
I am trying to calculate the occurrence list of each character in a word, my current codes looks like this:
"hello"
.groupBy((x:Char)=>x)
.map(a=>(a._1, a._2.length))
I think the .groupBy((x:Char)=>x)
looks clumsy and therefore rewrite like this:
"hello"
.groupBy(_)
.map(a=>(a._1, a._2.length))
But then the compiler throw an error
Error:(1, 18) missing parameter type for expanded function ((x$1) => "hello".groupBy(x$1).map(((a) => scala.Tuple2(a._1, a._2.length))))
"hello".groupBy(_).map(a=>(a._1, a._2.length))
^
Does anyone have ideas about this? Or is there better way to write this?
x.groupBy(_)
, like any method x.foo(_)
, means "turn this method into a function", i.e. y => x.groupBy(y)
.
Because _
is used for many things, it also can mean "plug in the value here". However, the "plug in identity" doesn't work because of the meaning above.
You can do x => x
or identity
to get what you intend by _
.
这篇关于在Scala中,为什么`_`不能在groupBy中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!