0

I am struggling to obtained the types of the arguments of a defined function in Scala. For example Funcion1[T1, T2].

Since Java will eliminate the types checking (compiler warning: is unchecked since it is eliminated by erasure), I would like to find a way to match that function with their types.

The goal is to be able to have same functionality as:

val fnInput = {x: Map[String, Double] => x}

fnInput match {
    case f: Function1[Map[String, Double], Map[String, Double]] => ???
    case f: Function1[T1, T2] => ???
    case f: Function2[T1, T2, T3] => ???
}

But, checking the arguments types.

Updated: so far my solution will go into using the following tools

import scala.reflect.runtime.universe._
def getType[T: TypeTag](obj: T) = typeOf[T]
val t = getType({x: Map[String, Any] => x})
// check first argument
typeOf[Map[String, Int]] <:< t.typeArgs(0)

// check return of Function1
typeOf[Map[String, Int]] <:< t.typeArgs(1)

// t.typeArgs.length will return the number of arguments +1

Do you believe that this is a good approach?

aitorhh
  • 2,331
  • 1
  • 23
  • 35
  • Are you sure you can't avoid the case of having such a vague thing defined as input? You're literally saying "I am expecting some function from something to something with some number of parameters which may or may not have different types". I find this to be very far away from any notion of clean and elegant FP code. But if it's unavoidable, you will have to resort to TypeTags or something similar (see [here](https://stackoverflow.com/questions/33708676/how-to-pattern-match-a-function-in-scala) for example). – slouc Sep 20 '18 at 09:46
  • I am actually having that question quite often... This does not seems the right approach. What I avoid explaining in the question is that the function `fnInput` is actually coming from a string. The string is compiled at runtime (using the toolbox), then I would like to check the function types to forward that to the underlying code. – aitorhh Sep 20 '18 at 10:39

0 Answers0