Scala:将 Seq 传递给 var-args 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1832061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:46:16  来源:igfitidea点击:

Scala: pass Seq to var-args functions

scala

提问by David Crawshaw

Given a function that takes a variable number of arguments, e.g.

给定一个带有可变数量参数的函数,例如

def foo(os: String*) =
  println(os.toList)

How can I pass a sequence of arguments to the function? I would like to write:

如何将参数序列传递给函数?我想写:

val args = Seq("hi", "there")
foo(args)

Obviously, this does not work.

显然,这行不通。

回答by Joa Ebert

foo(args:_*)does the trick. Instead of applying the sequence as one single argument, each element in the sequence will be used as an argument.

foo(args:_*)诀窍。不是将序列作为单个参数应用,而是将序列中的每个元素用作参数。