ssanj
ssanj

Reputation: 2179

Default parameters with currying

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 have to supply both parameters. Is there some way around this?

Upvotes: 8

Views: 1912

Answers (1)

Oleg Galako
Oleg Galako

Reputation: 1035

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)

Upvotes: 17

Related Questions