Scala中可变长度参数列表的类型是什么?

时间:2012-11-03 01:03:51

标签: scala variadic-functions

假设我声明一个函数如下:

def test(args: String*) = args mkString

args的类型是什么?

1 个答案:

答案 0 :(得分:33)

这称为可变数量的参数或简称varargs。它的静态类型为Seq[T],其中T代表T*。因为Seq[T]是一个接口,所以它不能用作实现,在本例中为scala.collection.mutable.WrappedArray[T]。要找出这些东西,使用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通常与_*符号结合使用,这是编译器将Seq[T]的元素传递给函数而不是序列本身的提示:

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)