Invocation of methods with default parameters in s

2019-08-11 03:26发布

问题:

Supposedly I have a method that has one default parameter. I want to pass it as an argument to another method. How do I call the passed-in method with its default parameter ?

def printNum(i: Int = 4): Unit = {
  println(i)
}

def doStuff(printFunc: (Int) => Unit): Unit = {
  // How to call printFunc with its default parameter 
  printFunc()
}

doStuff(printNum)

回答1:

I am afraid you cannot. Default parameter is property of methods, just like named arguments and things like this. When you pass it as a function, it get's converted to function with eta expansion and functions don't have default parameters.

Just look at this:

def doStuff(printFunc: Int => Unit): Unit = ???

It is a method that expects function Int => Unit, any function Int => Unit. So if you can pass arbitrary function, how compiler would know that it has a default parameter.

You could think of creating a wrapper for Function that has a default value and overloaded apply method. But it's still not easy to pull out the default argument from method to make it transparent.

What you can easly do is create another method

def printDefaultNum(): Unit = {
  printNum(4)
}

And make doStuff accept Function0 as you actually want to call it with no parameters.

def doStuff(printFunc: () => Unit): Unit = {
  printFunc()
}

doStuff(printDefaultNum)