Syntax of recursive variadic function in Scala [duplicate]

[亡魂溺海] 提交于 2019-12-12 15:27:57

问题


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)


回答1:


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".



来源:https://stackoverflow.com/questions/28527736/syntax-of-recursive-variadic-function-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!