0
votes

My requirement is to return a function from another function in scala which takes variable argument i.e while executing the returned function , i can pass multiple argument at runtime.

My code looks like :

object VarArgTest {
  def getFunction(): (Map[String, String],Map[String, Any]*) => Any={
    (arg:Map[String,String], arg2:Map[String,Any]*) => "random"//this gives compilation error
  }
}

In code , i want to return a function which take , Map[String,String] as one argument ,while the other Map[String,Any] should be optional to it.

But i get compilation error in return statement as follow:

type mismatch; found : (Map[String,String], Map[String,Any]) required: (Map[String,String], Map[String,Any]*) ⇒ Any

Can anyone help , what have i missed here? Note: My requirement is that returned function can take either one argument (Map[String,String]) or it can take two arguments max (Map[String,String], Map[String,Any])

Thanks

1

1 Answers

3
votes

It's impossible to use varargs in anonymous function. You can get your piece of code working by making the returned function nested instead of anonymous like this:

object VarArgTest {
  def getFunction(): (Map[String, String],Map[String, Any]*) => Any = {
    def nestedFunction(arg:Map[String,String], arg2:Map[String,Any]*) = "random"
    nestedFunction
  }
}

However since you don't need multiple instances of Map[String, Any] but either none or one, you would be better off using Option[Map[String, Any]], providing None when it is not needed.