How to pass an optional parameter to close a function?

I would like to pass method closure as an option, and I am doing what is shown below. I get a compilation error as shown below. Is it possible to pass an optional parameter to close the 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 
+6
source share
4 answers

The error message is pretty explicit: sampleMethod expects Option , but you pass a direct value to the function (not wrapped in Some ).

The easiest way to fix this is to wrap optMethod in Some :

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

But if you just want to make sampleMethod("hi", "bye", optMethod) , you can add overloaded sampleMethod definitions:

 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 
+7
source

As stated earlier, your method expects an Option value containing optionalMethod . Therefore, you must pass it the value of Option :

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

If you want to avoid the Option value (for example, avoid 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") 
+6
source

What about

 sampleMethod("hi", "bye", Some(optMethod)) 
+3
source

More clearly:

 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 should simply add "Some ()" around your optical function.

0
source

All Articles