vendredi 17 juin 2016

Scala types: reflect: Infer generic type parameter

I'm implementing some expressions using Scala type system.

I have a function

def f[T](arg: Option[T]): T = ???

The type of the function is

type F[T] = Option[T] => T

and at runtime can be represented with PolyType:

val tpe = weakTypeOf[F[_]].etaExpand // PolyType(T,Function1[Option[T],T])

Sometimes the valid argument can have one of the derived types: None|_:Some[Int]. (So the type is more precise).

I want to infer the result type of the function application to that argument f(arg): Int.

For Option[Int] it's more or less straight forward. For None I found a way via typeSignatureIn(_). But I cannot figure out a simple way to guess that T=:= Int in case of _:Some[Int].

Is there some type-inference helper methods in scala.reflect._ that can facilitate in solving this kind of problems?





Aucun commentaire:

Enregistrer un commentaire