Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax of recursive variadic function in Scala [duplicate]

I'm learning Scala and I just faced variadic functions. It's almost all ok on the example below I wrote:

object Sscce {

  def main(args: Array[String]) {
    printStrings("Hello", "Scala", "here", "I", "am");
  }

  def printStrings(ss: String*): Unit = {
    if (!ss.isEmpty) {
      println(ss.head)
      printStrings(ss.tail: _*)
    }
  }

}

I understand that String* means a variable list of strings and that ss is mapped to a Seq type. I also assume that a Seq cannot passed to a variadic function so in the recursive call of printStrings something has to be done with ss.

Question is: what is the exact meaning of : _*? It seems something like a cast to me (since there's the : symbol)

like image 991
giampaolo Avatar asked Jan 20 '26 17:01

giampaolo


1 Answers

It's called a sequence argument (see the second-to-last paragraph in section 6.6 Function Applications of the Scala Language Specification).

It deliberately resembles Type Ascription syntax. In an argument list, it basically means the exact opposite of what Repeated Parameters mean in a parameter list. Repeated parameters mean "take all the leftover arguments and collect them into a single Seq", whereas sequence arguments mean "take this single Seq and pass its elements as individual arguments".

like image 193
Jörg W Mittag Avatar answered Jan 23 '26 20:01

Jörg W Mittag