单个 arg 匿名函数的简明符号(避免下划线)未按预期工作 [英] Concise notation for single arg anonymous function (avoiding underscore) not working as expected
本文介绍了单个 arg 匿名函数的简明符号(避免下划线)未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在浏览了网络上的一些示例后,我意识到有一种方法可以在只有单个 arg 时编写不带下划线的匿名函数.另外,我正在尝试使用 List 上的span"方法,我从来不知道它存在.无论如何,这是我的 REPL 会话:
After going through some examples on the web I realize that there is a way to write an anonymous function without the underscore when only a single arg. Also, I'm experimenting with the "span" method on List, which I never knew existed. Anyway, here is my REPL session:
scala> val nums = List(1, 2, 3, 4, 5)
nums: List[Int] = List(1, 2, 3, 4, 5)
scala> nums span (_ != 3)
res0: (List[Int], List[Int]) = (List(1, 2),List(3, 4, 5))
scala> nums span (3 !=)
res1: (List[Int], List[Int]) = (List(1, 2),List(3, 4, 5))
到目前为止一切顺利.但是当我尝试使用小于"运算符时:
So far so good. But when I try to use the "less than" operator:
scala> nums span (_ < 3)
res2: (List[Int], List[Int]) = (List(1, 2),List(3, 4, 5))
scala> nums span (3 <)
res3: (List[Int], List[Int]) = (List(),List(1, 2, 3, 4, 5))
为什么这表现不同?
推荐答案
scala> nums span (_ < 3)
res0: (List[Int], List[Int]) = (List(1, 2),List(3, 4, 5))
scala> nums span (3 >)
res1: (List[Int], List[Int]) = (List(1, 2),List(3, 4, 5))
3
是
3
的快捷方式_
,它通过方法调用创建一个部分应用的函数.
3 <
is a shortcut to 3 < _
, which creates a partially applied function from method call.
这篇关于单个 arg 匿名函数的简明符号(避免下划线)未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文