Ian
Ian

Reputation: 1304

Pass Seq as parameters in Scala non-vararg method

I have a method in Scala that has a fixed number of parameters whose signature I cannot change:

def myMethod(a1: Int, a2: Int, a3: Int): Int = { /* stuff happens */ }

I also have an array arr with exactly the right number of elements as there are parameters in myMethod. If myMethod were a vararg method I could use the weird : _* notation to pass the array as parameters. I'd like to do something like

myMethod(/*some Scala magic with arr*/)

Is there a way to do that elegantly in Scala that does not require myMethod to be vararg?

Upvotes: 2

Views: 421

Answers (2)

Łukasz
Łukasz

Reputation: 8663

Note that you maybe maybe can't change a signature but you could add an overload through implicit conversion

class A {
  def myMethod(a1: Int, a2: Int, a3: Int): Int = 5
}

implicit class ExA(self: A) extends AnyVal {
  def myMethod(arr: Array[Int]): Int = {
    val Array(a1, a2, a3) = arr
    self.myMethod(a1, a2, a3)
  }
}

And then you simply can pass your array, if it is not 3 elements long you will get an error in runtime.

scala> (new A).myMethod(Array(1, 2, 3))
res2: Int = 5

Without any extra knowledge compiler can't be as sure as you about the size of array and thus there doesn't seem to be a way to just expand some arbitrary array into 3 arguments and put it into a function.

Upvotes: 3

Zoltán
Zoltán

Reputation: 22156

I think the closest you can come to that is to deconstruct your array in a step before invoking your method:

val Array(a1, a2, a3) = arr
myMethod(a1, a2, a3)

Upvotes: 5

Related Questions