mercredi 8 mars 2023

Determine the function signature of an anonymous function in scala

Suppose that there is a function that returns an anonymous function:

 def impl(): Function1[Int, String] = new Function1[Int, String] {
    def apply(x: Int): String = "ab" + x.toString
  }


  impl: ()Int => String

Now, impl() will return an anonymous function. Suppose that I do not know the signature of function because the impl function is implemented elsewhere, and I'd like to ask whether we can convert it into a correct function instance:

impl().asInstanceOf[Function1[Int, String]]   // How to determine the function signature of the anonymous function, in this case Function1[Int, String]?

Since scala does not support generic function, I first consider getting the runtime type of the function:

import scala.reflect.runtime.universe.{TypeTag, typeTag}
def getTypeTag[T: TypeTag](obj: T) = typeTag[T]
val typeList = getTypeTag(impl()).tpe.typeArgs

It will return List(Int, String), but I fail to recognize the correct function template via reflection.





Aucun commentaire:

Enregistrer un commentaire