假设我声明一个函数如下:
def test(args: String*) = args mkString
args
的类型是什么?
最佳答案
这称为可变数量的参数或简称为可变参数。它的静态类型是Seq[T]
,其中T
代表T*
。因为 Seq[T]
是一个接口(interface),所以不能用作实现,在本例中为 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)
关于scala - Scala 中可变长度参数列表的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13205012/