Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the type of a variable-length argument list in Scala?

Tags:

Suppose that I declare a function as follows:

def test(args: String*) = args mkString

What is the type of args?

like image 803
Evan Kroske Avatar asked Nov 03 '12 01:11

Evan Kroske


1 Answers

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)
like image 67
kiritsuku Avatar answered Sep 27 '22 21:09

kiritsuku