在函数文字中去掉下划线? [英] Leave off underscore in function literal?
问题描述
scala> val alist = List(1,2,3,4,5)
alist: List[Int] = List(1, 2, 3, 4, 5)
scala> alist filter { 2.< }
res2: List[Int] = List(3, 4, 5)
scala> alist filter { 2 < }
res3: List[Int] = List(3, 4, 5)
scala> alist filter { > 3 }
<console>:1: error: ';' expected but integer literal found.
alist filter { > 3 }
为什么 { 2.<}
和 {2 <}
工作吗?我想至少我应该写 { 2 <_ }
对吧?
Why would { 2.< }
and {2 <}
work? I think at least I should write { 2 < _ }
right?
不需要参数的方法,您也可以省略点号并使用后缀运算符表示法:
A method that requires no arguments, you can alternatively leave off the dot and use postfix operator notation:
scala> val s = "Hello, world!"
s: java.lang.String = Hello, world!
scala> s toLowerCase
res4: java.lang.String = hello, world!
但是这里,<
方法不是那种不需要参数的方法吧?
But here, <
method is not those kinds of methods which requires no arguments right?
你能指出这是什么用法吗?
Can you point me what is this usage?
推荐答案
正在发生的是 Eta 扩展 (6.26.5):
What is happening is an Eta Expansion (6.26.5):
Eta-expansion 将方法类型的表达式转换为等效的函数类型的表达.
Eta-expansion converts an expression of method type to an equivalent expression of function type.
在这种情况下,2 <
是一种方法类型:Int
上的方法 <
(之一).但是, filter
需要一个函数类型.在这种情况下,Scala 会自动进行 eta 扩展.
In this case, 2 <
is a method type: (one of) the method <
on Int
. However, filter
expects a function type. In such a case, Scala does automatic eta expansion.
请注意,因为 filter
预期的类型是已知的,所以它可以正确推断出正在调用的 2 <
方法.
Note that, because the type expected by filter
is known, it can correctly infer what 2 <
method is being called.
这篇关于在函数文字中去掉下划线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!