7

I would like to pass a closure to a method as an Option and I am doing what is shown below. I get a compile error as shown below. Is it possible to pass an optional closure parameter to a function?

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
3
  • sampleMethod("hi", "bye", Some(optMethod))
    – twillouer
    Feb 8, 2013 at 15:03
  • optionalMethod.map(f => f("a", 3)) to be more clear
    – twillouer
    Feb 8, 2013 at 15:04
  • 1
    Just 'cause other languages and their user communities are sloppy with terminology, let's not do the same here. "Closure" refers to the use of free variables in a function literal (names without bindings in that function's body) and having those references "close" into the lexical environment. Not all functions involve closing into the lexical environment. Not all functions are function literals. E.g., they are frequently created (either automatically and transparently by the compiler or explicitly) through "partial application" of another function or of a method. Feb 8, 2013 at 15:46

4 Answers 4

8

The error message is pretty explicit: sampleMethod expects an Option, but you are passing a straight function value (not wrapped in Some).

The simplest way to fix this is to wrap optMethod into a Some:

sampleMethod("hi", "bye", Some(optMethod))

But if you want to be able to simply do sampleMethod("hi", "bye", optMethod), you could add overloaded definitions of 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
4
  • I think overloading is a much better approach than using Option for the function argument. Feb 8, 2013 at 15:34
  • You mean using just 2 overloads (one with the argument and one without) as opposed to 3 overloads as in my answer? If so, the thing is that in the general case there might be enough common behaviour between both cases that you want to factorize that into a single implementation (as in my first overload which does all the work), and enough differences that just having a default value for optionalMethod (as in @ fynn's answer) might not be enough. It very much depends on the actual needs. Feb 8, 2013 at 15:59
  • 2
    Then make a private method that does the work and takes the Option[Function] which is then called by the public methods overloaded with and without the Function. Feb 8, 2013 at 16:19
  • This is exactly what I have done, except for the implementation being public rather than private. And I actually think it is better to have it public because it composes better: if at one point you get an Option[(String, Int) => Unit] value and want to pass it to sampleMethod it can be done immediately, but if the overload that takes an Option is private, I will have to match over the option and call one overload or another (plus duplicate the rest of the argument list). That's not a win to me. Feb 8, 2013 at 16:33
6

As pointed out earlier, your method expects an Option value containing the optionalMethod. You must hence pass an Option value to it:

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

If you want to avoid the Option value (esp. avoid the None), you can try the following:

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")
3

How about

sampleMethod("hi", "bye", Some(optMethod))
0

More clear :

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

You must just add "Some()" around your optinal function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.