Skip to content
Search

Scala:Vararg

lastmod 2020-09-11created 2020-09-111 edits

vararg, _* type annotation

Example

Explains how vararg is handled in Scala.

object Objective {
  def printAll(values: String *): Unit = {
    values.foreach(print)
  }
}

object Main extends App {
  Objective.printAll("aaaa", "bbbbbb")
  println()
  val vals = List("aaaa", "bbbbbb")
  Objective.printAll(vals : _*)
}

The result is as follows.

aaaabbbbbb
aaaabbbbbb

An expression such as String* defines a vararg of type String,

and the caller converts the List collection with : _* before passing it.

This may seem absurd to Java developers, but it is covered in section 4.6.2 Repeated Parameters of the Scala Language Specification. _* is referred to as a _* type annotation.

It is also called the Smooch operator or unpacker.

See also

Favorite site

author Zer0 sitemap