22

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

def test(args: String*) = args mkString

是什么类型的args

4

1 回答 1

33

这称为可变数量的参数或简称为可变参数。它的静态类型是Seq[T]whereT代表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 通常与_*符号结合使用,这是对编译器将 a 的元素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)
于 2012-11-03T10:50:48.073 回答