Java makes an assumption that you want to automatically convert the Array args
to varargs, but this can be problematic with methods that accept varargs of type Object.
Scala requires that you be explicit, by ascribing the argument with : _*
.
scala> def bar(args:String*) = println("count="+args.length)
bar: (args: String*)Unit
scala> def foo(args:String*) = bar(args: _*)
foo: (args: String*)Unit
scala> foo("1", "2")
count=2
You can use : _*
on any subtype of Seq
, or on anything implicitly convertable to a Seq
, notably Array
.
scala> def foo(is: Int*) = is.length
foo: (is: Int*)Int
scala> foo(1, 2, 3)
res0: Int = 3
scala> foo(Seq(1, 2, 3): _*)
res1: Int = 3
scala> foo(List(1, 2, 3): _*)
res2: Int = 3
scala> foo(Array(1, 2, 3): _*)
res3: Int = 3
scala> import collection.JavaConversions._
import collection.JavaConversions._
scala> foo(java.util.Arrays.asList(1, 2, 3): _*)
res6: Int = 3
It is explained well with examples in the Language Reference, in section 4.6.2.
Note that these examples are made with Scala 2.8.0.RC2.