假设我有一个不可犯的(是的,我知道它不能符合func())代码的cuz
def withCondition(func: (Nothing) => Int): Unit =
if (someExtConditionIsTrue) func()
但是我想与此包装器一起使用的功能看起来像
def func(a: Int = 5) = a * 2
有什么办法可以在包装器内使用其自己的 default 参数在包装器中调用函数,而我不知道该函数到底是什么,什么是默认参数值?
P.S。:我通过使a
的选项找到解决方法或检查任何位置,但问题仍然存在。
这是一个合法函数,它正确使用默认参数:
def func(a: Int = 5) = a * 2
此功能的类型为:Int => Int
。
此代码不编译:
def withCondition(func: (Nothing) => Any): Unit =
if (someExtConditionIsTrue) func()
因为您的func
预计将通过Nothing
型的东西。也许您的意思是拥有一个不使用ARG的函数:
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
编辑
调用具有默认ARG的函数您可以使用:
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且不采用args的函数。在这种情况下,在将其传递给包装器函数之前,您必须为该函数提供该值,因为包装器函数不能将任何ARG传递给不使用ARG的函数。在您的情况下,您要么通过使用默认ARG或明确将ARG传递给func
,就像上面的示例一样。