带有currying的默认参数

时间:2011-02-22 05:35:30

标签: scala parameters currying

我可以将函数定义为:

def print(n:Int, s:String = "blah") {}
print: (n: Int,s: String)Unit

我可以用:

来调用它
print(5) 
print(5, "testing")

如果我讨论上述情况:

def print2(n:Int)(s:String = "blah") {} 
print2: (n: Int)(s: String)Unit

我不能用1参数调用它:

print2(5)
<console>:7: error: missing arguments for method print2 in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
       print2(5)

我必须提供这两个参数。有什么方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:17)

您不能使用默认参数省略()

scala> def print2(n:Int)(s:String = "blah") {}
print2: (n: Int)(s: String)Unit

scala> print2(5)()

虽然它适用于暗示:

scala> case class SecondParam(s: String)
defined class SecondParam

scala> def print2(n:Int)(implicit s: SecondParam = SecondParam("blah")) {}
print2: (n: Int)(implicit s: SecondParam)Unit

scala> print2(5)