Scala 中递归可变参数函数的语法 [英] Syntax of recursive variadic function in Scala

查看:35
本文介绍了Scala 中递归可变参数函数的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Scala,但我刚刚遇到了可变参数函数.在我写的下面的例子中几乎没问题:

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: _*)
    }
  }

}

我知道 String* 表示字符串的变量列表,并且 ss 映射到 Seq 类型.我还假设 Seq 不能传递给可变参数函数,所以在 printStrings 的递归调用中,必须用 ss 做一些事情.

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)

推荐答案

它被称为序列参数(参见 Scala 语言规范第 6.6 节 函数应用>).

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

它故意类似于 类型归属 语法.在参数列表中,它基本上意味着与 重复参数 表示在参数列表中.重复参数意味着获取所有剩余的参数并将它们收集到一个 Seq"中,而序列参数意味着获取这个单个 Seq 并将其元素作为单独的参数传递".

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

这篇关于Scala 中递归可变参数函数的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆