0

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

0

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.