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

时间:2022-03-31 11:01:15

I have a function called or for example, which is defined as;

我有一个叫做的函数,例如,定义为;

or(filters: FilterDefinition*)

And then I have a list:

然后我有一个清单:

List(X, Y, Z)

What I now need to do is call or like

我现在需要做的就是打电话或者喜欢

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中执行此操作的最佳方法是什么?

1 个解决方案

#1


37  

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

#1


37  

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