Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First parameter as default in Scala

Tags:

scala

default

Is there another way of making this work?

def b(first:String="hello",second:String) = println("first:"+first+" second:"+second)

b(second="geo")

If I call the method with just:

b("geo")

I get:

<console>:7: error: not enough arguments for method b: (first: String,second: String)Unit.
Unspecified value parameter second.
       b("geo")
like image 918
Geo Avatar asked Feb 03 '26 13:02

Geo


2 Answers

Here is one of the possible ways: you can use several argument lists and currying:

scala> def b(first:String="hello")(second:String) = println("first:"+first+" second:"+second)
b: (first: String)(second: String)Unit

scala> b()("Scala")
first:hello second:Scala

scala> val c = b() _
c: (String) => Unit = <function1>

scala> c("Scala")
first:hello second:Scala
like image 51
tenshi Avatar answered Feb 06 '26 03:02

tenshi


See scala language specifications 6.6.1 (http://www.scala-lang.org/docu/files/ScalaReference.pdf):

"The named arguments form a suffix of the argument list e1, ..., em, i.e. no positional argument follows a named one."

like image 34
thoredge Avatar answered Feb 06 '26 03:02

thoredge