I'm making a function that takes a lambda, and uses .tupled
on it if possible (arity 2+). For the compiler to allow using that, it needs to know if the lambda is really a Function2 (~ Function22). However, pattern-matching for Function2[Any,Any,Any]
means I'm left with a (Any, Any) => Any
rather than its original types. Not even knowing the arity isn't helping either. I tried matching like case f[A <: Any, B <: Any, C <: Any]: scala.Function2[A, B, C] => f.tupled
in an attempt to preserve types, but it doesn't really allow type parameters on a case.
The code:
val add = (a: Int, b: Int) => a + b
add: (Int, Int) => Int = <function2>
val tpl = (fn: Any) => {
fn match {
case f: Function0[Any] => f
case f: Function1[Any,Any] => f
case f: Function2[Any,Any,Any] => f.tupled
// case f: Function3[Any,Any,Any,Any] => f.tupled
// ...
// case _ => { throw new Exception("huh") }
}
}
// actual result:
tpl(add)
res0: Any = <function1>
// desired result is like this one:
scala> add.tupled
res3: ((Int, Int)) => Int = <function1>
Bonus points if I won't need pattern-matching cases for each possible level of arity...