I don't think you can do it in standard Scala in a typesafe way, but it's possible to do it using the Shapeless library. Even if you don't use this library in the project, you can depend on it only for the test scope.
Here is the code sample:
import shapeless._
import shapeless.ops.function._
import shapeless.ops.traversable._
def applyToList[F, HL <: HList, R](f: F)(args: List[Any])(implicit
// convert `(T1, T2, ...) => R` to a function from a single HList argument `HL => R`
fnToProduct: FnToProduct.Aux[F, HL => R],
// convert the argument list to the HList, expected by the converted function
toHList: FromTraversable[HL]
): R = {
toHList(args) match {
case Some(hargs) => fnToProduct(f)(hargs)
case None => sys.error("argument list not applicable to function")
}
}
Using it is as simple as this:
def f(a: Int, b: Int, c: Int, d: Int): Any = ???
applyToList(f _)(List(1, 2, 3, 4))
But notice the need for an explicit eta-conversion f _
, because the Scala compiler doesn't really know, that F
is a function.
You can change the definition to return Option[R]
, because it's impossible to know at compile-time if the provided List
will fit the function or not. For example, the argument list may have a non-matching number of elements. But if this is for unit-tests, you may as well just throw an exception.