user568109
user568109

Reputation: 48013

Break array and pass as arguments in scala

I am new to scala so forgive me if this is easy to do.

I have an array consisting of values that I need to pass to a function. But the function accepts multiple arguments. The arguments are present but how do I break the array and pass it to the function?

In short I have array [1,2,3] and I want to call func(1,2,3).

Upvotes: 0

Views: 1293

Answers (3)

user568109
user568109

Reputation: 48013

Found it. For def func(a: Int*) it can be done with:

func(arr:_*)

Upvotes: 1

Alexey Romanov
Alexey Romanov

Reputation: 170899

If your function takes varargs (such as Int*), then the solution in your reply works; however, if it actually takes multiple arguments, it doesn't. In this case you need to do func(arr(0), arr(1), arr(2)) or use reflection:

// assumes func has exactly one apply method, modify to taste
val method = func.getClass.getMethods.filter(_.getName == "apply").head
method.invoke(func, arr)

Upvotes: 1

Sergii Lagutin
Sergii Lagutin

Reputation: 10681

Use apply to get element by index:

val a = Array(1,2,3)
func(a(0), a(1), a(2))

or other way:

val Array(a,b,c,_) = Array(1,2,3,4,5)
func(a,b,c)

Upvotes: 3

Related Questions