简体   繁体   中英

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(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?

Take a look at this example, I will define a function printme that takes vargs of type String

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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