What is the type of a variable-length argument list in Scala?
10,346
This is called a variable number of arguments or in short varargs. It's static type is Seq[T]
where T
represents T*
. Because Seq[T]
is an interface it can't be used as an implementation, which is in this case scala.collection.mutable.WrappedArray[T]
. To find out such things it can be useful to use the REPL:
// static type
scala> def test(args: String*) = args
test: (args: String*)Seq[String]
// runtime type
scala> def test(args: String*) = args.getClass.getName
test: (args: String*)String
scala> test("")
res2: String = scala.collection.mutable.WrappedArray$ofRef
Varargs are often used in combination with the _*
symbol, which is a hint to the compiler to pass the elements of a Seq[T]
to a function instead of the sequence itself:
scala> def test[T](seq: T*) = seq
test: [T](seq: T*)Seq[T]
// result contains the sequence
scala> test(Seq(1,2,3))
res3: Seq[Seq[Int]] = WrappedArray(List(1, 2, 3))
// result contains elements of the sequence
scala> test(Seq(1,2,3): _*)
res4: Seq[Int] = List(1, 2, 3)
Related videos on Youtube
Comments
-
Evan Kroske over 1 year
Suppose that I declare a function as follows:
def test(args: String*) = args mkString
What is the type of
args
? -
Val almost 9 yearsYes, this has and interesting effect that you cannot pass the var-len args immediately,
def f1(args: Int*) = args.length; def f2(args: Int*) = f1(args)
. It will givefound Seq[Int] whereas Int is required mismatch error
in f2 definition. To circumvent, you need todef f2 = f1(args: _*)
. So, compiler thinks that argument is a single value and sequence at the same, at compile time :) -
dpetters almost 3 yearsAs of Scala
2.13.6
, the implementation ofSeq
used isscala.collection.immutable.ArraySeq
.