在Scala高阶函数中调用具有默认参数的方法 [英] Invocation of methods with default parameters in scala higher-order function
问题描述
据说我有一个带有一个默认参数的方法.我想将其作为参数传递给另一种方法.如何使用默认参数调用传入的方法?
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)
推荐答案
恐怕您不能.默认参数是方法的属性,就像命名参数和类似的东西一样.当您将其作为函数传递时,它将转换为具有eta扩展的函数,并且函数没有默认参数.
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.
只要看看这个:
def doStuff(printFunc: Int => Unit): Unit = ???
这是需要函数Int => Unit
和任何函数Int => 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.
您可以考虑为Function
创建一个包装器,该包装器具有默认值和重载的apply
方法.但是从方法中拉出默认参数以使其透明仍然不容易.
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)
}
并让doStuff
接受Function0
,因为您实际上想不带任何参数调用它.
And make doStuff
accept Function0
as you actually want to call it with no parameters.
def doStuff(printFunc: () => Unit): Unit = {
printFunc()
}
doStuff(printDefaultNum)
这篇关于在Scala高阶函数中调用具有默认参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!