Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

variadic functions - 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

What is the type of args?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...