What is the type of a variable-length argument lis

2020-01-31 02:39发布

问题:

Suppose that I declare a function as follows:

def test(args: String*) = args mkString

What is the type of args?

回答1:

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)