7

我想将一个闭包作为选项传递给一个方法,我正在做如下所示的事情。我收到如下所示的编译错误。是否可以将可选的闭包参数传​​递给函数?

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
4

4 回答 4

8

错误消息非常明确:sampleMethod需要一个Option,但您传递的是一个直接的函数值(未包含在 中Some)。

解决这个问题的最简单方法是包装optMethodSome

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
于 2013-02-08T15:16:50.837 回答
6

如前所述,您的方法需要一个Option包含optionalMethod. 因此,您必须将Option值传递给它:

// invoke with method
sampleMethod("hi", "bye", Some(optMethod))
// invoke without method
sampleMethod("hi", "bye", None)

如果您想避免该Option值(尤其是避免None),您可以尝试以下操作:

def sampleMethod(a: String, b: String, optionalMethod: (String, Int) => Unit = (_, _) => log("no optional method passed")) {
  optionalMethod("a", 3)
}

// invoke with method
sampleMethod("hi", "bye", optMethod)
// invoke without method
sampleMethod("hi", "bye")
于 2013-02-08T15:01:54.697 回答
3

怎么样

sampleMethod("hi", "bye", Some(optMethod))
于 2013-02-08T14:52:27.267 回答
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()”

于 2013-02-08T15:07:44.283 回答