简体   繁体   English

将List的元素作为参数传递给具有可变参数的函数

[英]Passing elements of a List as parameters to a function with variable arguments

I have a function called or for 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 or like 我现在需要做的是打电话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中执行此操作的最佳方法是什么?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM