这是一个合法的函数,它正确地使用了默认参数:
def func(a: Int = 5) = a * 2
这个函数的类型是:Int => Int。
此代码无法编译:
def withCondition(func: (Nothing) => Any): Unit =
if (someExtConditionIsTrue) func()
因为您的func 预计会传递Nothing 类型的东西。也许你的意思是有一个不带参数的函数:
def withCondition(func: => Int): Unit =
if (someExtConditionIsTrue) func()
或者您可以将默认参数“推送”到包装函数:
def withCondition(func: Int => Int, a: Int = 5): Unit =
if (someExtConditionIsTrue) func(a)
// call it:
withCondition(func)
您可以尝试使用隐式参数而不是默认参数,如下所示:
implicit val defaultArg = 5
然后:
def withCondition(func: Int => Int)(implicit a: Int): Unit = func(a)
或直接传给func:
def func(implicit a: Int) = a * 2
编辑
要调用具有默认参数的函数,您可以使用:
scala> def withCondition(func: => Int): Unit = println(func)
withCondition: (func: => Int)Unit
scala> def func(a: Int = 5) = a * 2
func: (a: Int)Int
scala> withCondition(func())
10
// or
scala> withCondition(func(3))
6
如果你使用这种形式:def withCondition(func: => Int) 那么这意味着它需要一个返回 Int 且不带参数的函数。在这种情况下,您必须在将函数传递给包装函数之前为该函数提供该值,因为包装函数不能将任何参数传递给不接受参数的函数。在您的情况下,您可以通过使用默认 arg 或通过显式将 arg 传递给 func 来实现这一点,就像上面的示例一样。