开发者

Default parameters with currying

开发者 https://www.devze.com 2023-02-12 18:27 出处:网络
I can define a function as: def print(n:Int, s:String = \"blah\") {} print: (n: Int,s: String)Unit I can call it with:

I can define a function as:

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

I can call it with:

print(5) 
print(5, "testing")

If I curry the above:

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

I can't call it with 1 parameter:

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)

I hav开发者_如何学Goe to supply both parameters. Is there some way around this?


You can't omit () with default arguments:

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

scala> print2(5)()

Though it works with implicits:

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消