Invocation of methods with default parameters in scala higher-order function

自古美人都是妖i 提交于 2020-01-05 13:38:11

问题


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)


来源:https://stackoverflow.com/questions/36605572/invocation-of-methods-with-default-parameters-in-scala-higher-order-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!