Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Why can't a method have multiple vararg arguments?

Can anyone tell me why this limitation exists ? Is it related to JVM or Scala compiler ?

$ scala
Welcome to Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_79).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def toText(ints: Int*, strings: String*) = ints.mkString("") + strings.mkString("")
<console>:7: error: *-parameter must come last
       def toText(ints: Int*, strings: String*) = ints.mkString("") + strings.mkString("")
like image 901
Sudheer Aedama Avatar asked Dec 02 '22 17:12

Sudheer Aedama


1 Answers

A method in Scala can have multiple varargs if you use multiple parameter lists (curried syntax):

scala> def toText(ints: Int*)(strings: String*) = 
         ints.mkString("") + strings.mkString("")

scala> toText(1,2,3)("a", "b")

res0: String = 123ab

Update: Multiple varargs in a single parameter list would create a syntax problem - how would the compiler know which parameter a given argument belongs to (where does one list of arguments end, and the next begin, especially if they are of compatible types?).

In theory, if the syntax of the language were modified so that one could distinguish the first and second argument lists (without currying), there's no reason this wouldn't work at the JVM level, because varargs are just compiled into an array anyway.

But I very much doubt that it's a common enough case to justify complicating the language further, especially when a solution already exists.

See also this related Java question and answer.

like image 152
DNA Avatar answered Jan 10 '23 23:01

DNA