我想将一个闭包传递给一个方法作为Option,我正在做如下所示的事情。我收到编译错误,如下所示。是否可以将可选的闭包参数传递给函数?
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
答案 0 :(得分:8)
错误消息非常明确:sampleMethod
需要Option
,但您传递的是直接函数值(未包含在Some
中)。
解决此问题的最简单方法是将optMethod
包裹到Some
中:
sampleMethod("hi", "bye", Some(optMethod))
但是,如果您希望能够简单地执行sampleMethod("hi", "bye", optMethod)
,则可以添加sampleMethod
的重载定义:
object Test {
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")
}
}
def sampleMethod(a: String, b: String) { sampleMethod(a, b, None) }
def sampleMethod(a: String, b: String, optionalMethod: (String, Int) => Unit) {
sampleMethod(a, b, Some(optionalMethod))
}
}
val optMethod = (c: String, d: Int) => {
// some processing with c, d and external values
}
// invoke
Test.sampleMethod("hi", "bye", optMethod) // Now Compiles fine
Test.sampleMethod("hi", "bye") // This too
答案 1 :(得分:6)
如前所述,您的方法需要包含Option
的{{1}}值。因此,您必须将optionalMethod
值传递给它:
Option
如果您想避开// invoke with method
sampleMethod("hi", "bye", Some(optMethod))
// invoke without method
sampleMethod("hi", "bye", None)
值(尤其是避免Option
),您可以尝试以下操作:
None
答案 2 :(得分:3)
怎么样
sampleMethod("hi", "bye", Some(optMethod))
答案 3 :(得分:0)
更清楚:
scala> def sampleMethod(a: String, b: String, optionalMethod: Option[(String, Int) => Unit]) {
| optionalMethod.map(f => f("a", 3))
| }
sampleMethod: (a: String, b: String, optionalMethod: Option[(String, Int) => Unit])Unit
scala> sampleMethod("A", "A", Some((c:String, d:Int) => println(s"Hello wolrd $c...$d")))
Hello wolrd a...3
您必须在可选功能
周围添加“Some()”