scalagenericsreflectionscala-reflect

Is there a better way to test the generic type (without type arguments) in Scala?


Given I'm using reflection to go through a list of members (giving me runtime.universe.Symbol), how can I check the generic type without the type arguments? In other words, how do I find the members which are List[] generic type, regardless of what the type argument is?

Currently I'm using this approach which does work, but I'm wondering if there's a better way to do it:

import scala.reflect.runtime.currentMirror

// ...

val listTypeConstructor = typeOf[List[_]].typeConstructor
val myListMembers = currentMirror.reflect(MyObject)
  .symbol
  .asClass
  .typeSignature
  .members
  .filter(member => member.typeSignature.resultType.typeConstructor == listTypeConstructor)

This results in a list of runtime.universe.Symbol of all the List[] members, including any List[String], List[Int], etc. as expected.

The usage of typeOf[List[_]].typeConstructor seems a bit messy to me though. Is this the best way to do this kind of filtering?


Solution

  • The answer is no. The way I have it in the example above is the standard way.