Scala 中可变长度参数列表的类型是什么? [英] What is the type of a variable-length argument list in Scala?
问题描述
假设我声明一个函数如下:
Suppose that I declare a function as follows:
def test(args: String*) = args mkString
args
的类型是什么?
推荐答案
这称为可变数量的参数或简称为可变参数.它的静态类型是 Seq[T]
,其中 T
代表 T*
.因为 Seq[T]
是一个接口,它不能用作实现,在这种情况下是 scala.collection.mutable.WrappedArray[T]
.要找出这些东西,使用 REPL 会很有用:
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 经常与 _*
符号结合使用,它提示编译器将 Seq[T]
的元素传递给函数序列本身:
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)
这篇关于Scala 中可变长度参数列表的类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!