user48956
user48956

Reputation: 15810

How to look up the type of a method returning a type parameter with scala reflection?

trait F[S]{
  def evaluate(): S
}

From typeOf[F[Double]] how can find that the return type of "evaluate" is Double?

typeOf[F[Double]]
 .decls
 .filter(_.name.toString=="evaluate")
 .head
 .asMethod
 .returnType
 .dealias

==> S

The type information that evaluate returns a double hasn't been erased -- it just seems like its hard to look up and match up with the type parameters:

typeOf[F[Double]].typeArgs 

==> List(Double)

Its possible that my classes may have many type parameters, so I can't be sure that S is the first type parameter, but the types of the type parameters seem to be known.

Upvotes: 2

Views: 32

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

You can use asSeenFrom.

val tpe = typeOf[F[Double]]

tpe.decls
  .filter(_.name.toString == "evaluate")
  .head
  .asMethod
  .returnType
  .asSeenFrom(tpe, tpe.typeSymbol)

Upvotes: 3

Related Questions