Scala 方法类型和方法作为参数 [英] Scala method types and methods as parameters
问题描述
在下面的代码示例中,我不明白为什么函数 fun 可以作为参数传递给方法 addAction
.方法 fun
是 Unit
类型,而 addAction
方法需要 () => Unit
类型的函数.
In the following code example, I do not understand why the function fun can be passed as an argument to the method addAction
. The method fun
is of type Unit
, while the method addAction
expects a function of type () => Unit
.
如果 fun
是 () => Unit
类型,那么为什么编译器会抱怨 fun
是 Unit 类型
,当我尝试将 fun
添加到操作列表时: actions = fun :: actions
?
If fun
is of type () => Unit
, then why does the compiler complain that fun
is of type Unit
, when I try to add fun
to the actions list: actions = fun :: actions
?
package myscala
object MyScala {
def fun() { println("fun1 executed.") }
def addAction(a: () => Unit) {
actions = a :: actions
}
var actions: List[() => Unit] = List()
def main(args: Array[String]) {
// the following line would produce a compiler error (found: Unit, required: () => Unit), it's OK
// actions = fun :: actions
actions = (() => fun) :: actions // OK
// I would expect the same compiler error here (found: Unit, required: () => Unit), but it's OK why?
addAction(fun)
actions.foreach(_()) // prints twice "fun1 executed"
}
}
推荐答案
以此为介绍性示例:
def fun() { println("fun1 executed.") }
val a1 = fun
val a2: () => Unit = fun
这两行都可以编译并且(由于类型推断)它们看起来是等效的.但是 a1
是 Unit
类型,而 a2
是 () => 类型.单位
...这怎么可能?
Both lines compile and (thanks to type inference) they look equivalent. However a1
is of type Unit
while a2
is of type () => Unit
... How is this possible?
由于您没有明确提供a1
的类型,编译器将fun
解释为Unit类型的方法
fun
调用code>,因此a1
的类型与fun
的类型相同.这也意味着这一行将打印 fun1 执行.
Since you are not explicitly providing type of a1
, compilers interprets fun
as a method fun
call of type Unit
, hence the type of a1
is the same as type of fun
. It also means that this line will print fun1 executed.
然而,a2
已经明确声明了 () => 的类型.单位
.编译器在这里帮助你,它理解因为上下文需要一个 () => 类型的函数;Unit
并且你提供了一个匹配这个类型的方法,它不应该调用那个方法,而是把它当作一等函数!
However, a2
has explicitly declared type of () => Unit
. The compiler helps you here and it understands that since the context requires a function of type () => Unit
and you provided a method matching this type, it shouldn't call that method, but treat it as first class function!
你不是注定要明确指定a1
的类型.说:
You are not doomed to specify type of a1
explicitly. Saying:
val a1 = fun _
您现在明白问题出在哪里了吗?
Do you now understand where your problem is?
这篇关于Scala 方法类型和方法作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!