我想将一个闭包传递给一个方法作为一个选项,我正在做如下所示。我得到一个编译错误,如下所示。是否可以将一个可选的闭包参数传递给一个函数?如何将可选的闭包参数传递给函数?
def sampleMethod(a: String, b: String, optionalMethod: Option[(String, Int) => Unit]) {
// do some processing with a and b
optionalMethod match {
case Some(optionalMethod) => {
optionalMethod("a",3)
}
case _
log("no optional method passed")
}
}
// definition of optMethod in some other place
val optMethod = (c: String, d: Int) => {
// some processing with c, d and external values
}
// invoke
sampleMethod("hi", "bye", optMethod) => FAILS TO COMPILE
ERROR = type mismatch. expecting Option[(String, Int) => Unit] found (String, Int) => Unit
sampleMethod(“hi”,“bye”,Some(optMethod)) – twillouer 2013-02-08 15:03:49
optionalMethod.map(f => f(“a”,3))更清晰 – twillouer 2013-02-08 15:04:36
只是因为其他语言及其用户群体sl with不乐termino逻辑,我们不要在这里做同样的事情。 “关闭”是指在函数文字中使用自由变量(在该函数的主体中没有绑定的名称),并将这些引用“关闭”到词法环境中。并非所有功能都涉及到关闭词汇环境。并非所有函数都是函数文字。例如,它们经常通过另一个功能或方法的“部分应用”来创建(由编译器自动或透明地编译或显式地创建)。 – 2013-02-08 15:46:47