Scala 占位符语法 [英] Scala placeholder syntax
本文介绍了Scala 占位符语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有些东西我不太明白,希望有人能解释一下..我有 Seq[String]
There is something that I can't quite understand hope someone can shed some light.. I have Seq[String]
val strDeps: Seq[String] = ...
我尝试使用 sortWith 方法对它进行反向排序,但出现以下错误.
and I tried to sort it on the reverse of the using the sortWith method and I get the following error.
scala> print(strDeps.sortWith(_.reverse.compareTo(_.reverse) < 0) mkString ("\n"))
<console>:15: error: wrong number of parameters; expected = 2
print(strDeps.sortWith(_.reverse.compareTo(_.reverse) < 0) mkString ("\n"))
^
但是当我尝试对其进行排序而不进行反向操作时,它工作正常.
But when I try sort it without doing a reverse it works fine.
scala> print(strDeps.sortWith(_.compareTo(_) < 0) mkString ("\n"))
// this is fine
也可以在没有占位符语法的情况下正常工作
Also it works fine without the placeholder syntax
scala> print(strDeps.sortWith((a,b) => a.reverse.compareTo(b.reverse) < 0) mkString ("\n"))
// this works fine too
推荐答案
_
仅扩展到尽可能小的范围.
_
expands only to the smallest possible scope.
内部 _.reverse
部分已经被解释为 x =>x.reverse
因此参数在 sortWith
中丢失.
The inner _.reverse
part is already interpreted as x => x.reverse
therefore the parameter is missing inside sortWith
.
这篇关于Scala 占位符语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文