使用未知默认参数调用Scala函数

时间:2014-02-03 14:12:56

标签: function scala default-value

让我说我有一个无法编译的(是的,我知道它不能被编译为func())代码

 def withCondition(func: (Nothing) => Int): Unit = 
     if (someExtConditionIsTrue) func()

但我想用这个包装器的函数看起来像

def func(a: Int = 5) = a * 2

有没有什么方法可以在包装器中使用它自己的默认参数调用这样的函数,而我不知道该函数到底是什么以及它的默认参数值是什么?

P.S。:我通过制作a一个选项找到了解决方法,或者检查它在哪里为null,但问题仍然存在。

1 个答案:

答案 0 :(得分:4)

这是一个合法的功能,它正确使用默认参数:

def func(a: Int = 5) = a * 2

此功能的类型为:Int => Int

此代码无法编译:

def withCondition(func: (Nothing) => Any): Unit = 
  if (someExtConditionIsTrue) func()

因为您的func预计会传递Nothing类型的内容。也许你的意思是拥有一个不带args的函数:

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的函数。在这种情况下,您必须在将函数传递给包装函数之前为该函数提供该值,因为包装函数无法将任何args传递给不带args的函数。在您的情况下,您可以通过使用默认arg或通过显式将arg传递给func来实现,如上例所示。