Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

function

scala

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?

like image 701
Ashesh Avatar asked Sep 12 '14 19:09

Ashesh


People also ask

How do you pass a list of arguments to a function in Python?

In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.

Can you pass a list to * args?

yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.

How do you pass a variable to a list in Python?

In Python, we can use *args to pass a variable number of arguments to a function. Now, since a list has multiple values, people tend to use *args as the parameter variable for a list argument so that all the values of the list are taken care of.


1 Answers

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 
like image 119
Ahmed Farghal Avatar answered Oct 05 '22 15:10

Ahmed Farghal