scala 将 List 的元素作为参数传递给具有可变参数的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25815576/
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
Passing elements of a List as parameters to a function with variable arguments
提问by Ashesh
I have a function called orfor example, which is defined as;
or例如,我有一个名为的函数,它被定义为;
or(filters: FilterDefinition*)
And then I have a list:
然后我有一个清单:
List(X, Y, Z)
What I now need to do is call orlike
我现在需要做的是调用or像
or(func(X), func(Y), func(Z))
And as expected the length of the list may change.
正如预期的那样,列表的长度可能会发生变化。
What's the best way to do this in Scala?
在 Scala 中执行此操作的最佳方法是什么?
回答by Ahmed Soliman Farghal
Take a look at this example, I will define a function printme that takes vargs of type String
看一下这个例子,我将定义一个函数printme,它接受String类型的vargs
def printme(s: String*) = s.foreach(println)
scala> printme(List("a","b","c"))
<console>:9: error: type mismatch;
found : List[String]
required: String
printme(List(a,b,c))
What you really need to un-pack the list into arguments with the :_*operator
您真正需要使用:_*运算符将列表解压缩为参数
scala> val mylist = List("1","2","3")
scala> printme(mylist:_*)
1
2
3

