scala_newbie
scala_newbie

Reputation: 3465

pass function arguments from a iterable in Scala?

Is it possible to pass function arguments from a iterable in Scala?

val arguments= List(1,2)
def mysum(a:Int,b:Int)={a+b}

How would one call mysum using the List contents as arguments?

Upvotes: 4

Views: 1273

Answers (1)

Nikita Volkov
Nikita Volkov

Reputation: 43309

For it to work on lists you'll need to accomodate the mysum function to "varargs":

scala> def mysum ( args : Int* ) = args.sum
mysum: (args: Int*)Int

scala> val arguments = List(1,2)
arguments: List[Int] = List(1, 2)

scala> mysum(arguments: _*)
res0: Int = 3

Upvotes: 3

Related Questions