31

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?

Ashesh
  • 2,978
  • 4
  • 27
  • 47
  • 3
    Not exactly the same question but it gives the `: _*` notation which is the key to the answer (assuming you can just `list.map(func)`!): http://stackoverflow.com/questions/1008783 – Rex Kerr Sep 12 '14 at 19:48
  • If we pass the whole list elements and process all of them in the called function, then it can also be done by just passing the list to the function and the function can iterate thru the elements, without the need for special syntax of :_* ,right? Or I may be wrong, is there any good reason for this usage? – user3366706 Sep 13 '14 at 17:10
  • @user3366706 that would be the more traditional approach to do things, yes. For me this came in incredibly handy when dealing with a DSL that expected a generated query as the function argument – with variable number of arguments. – Ashesh Sep 15 '14 at 10:32

1 Answers1

69

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
Ahmed Farghal
  • 1,294
  • 11
  • 17