0

I am looking for a generalized solution to this problem for any sized number of parameters (well any, I don't mean over 15 parameters realistically) I have a function.

def test(a: String, b: Int): Int = 0

I have a Seq[Any].

val seq: Seq[Any] = Seq("Hi", 5)

How can I call the function test with this seq as the parameters?

Now I tried test(seq:_*) but that does not work because it does not match the function types, compiler cannot understand which function to use.

Could Scala Macros be useful here?

(You are looking at this and thinking, this is a bad idea, why have a Seq[Any] in the first place? Its bad practice, yes it is, but its a question, I'm not asking if its a good idea or not as I know its not good, I have a Seq[Any] and I start from there with the problem)

Phil
  • 46,436
  • 33
  • 110
  • 175

2 Answers2

5

Not sure this requirement is a good idea, but consider shapeless approach:

import shapeless._
import HList._
import syntax.std.traversable._

def test(a: String, b: Int): Int = 0
val seq = Seq("Hi", 5)
val tupledSeq = seq.toHList[String::Int::HNil].get.tupled
(test _).tupled(tupledSeq)

which outputs

res0: Int = 0

Note how we create tupled version of method test:

(test _).tupled
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
0

If I understand correctly, below code is what you want to do.

def test(params: Any*) = {
   params.map(p => ...) // params: Seq[Any]
   ???
}

test(Seq("Hello", 1):_*)

It's mostly not a good practice, though, unless you have an exceptional scenario, like calling a method in a third party library which mandates Any* as its parameter type.

Feyyaz
  • 3,147
  • 4
  • 35
  • 50