Note that there are some explanatory texts on larger screens.

plurals
  1. POFinding type parameters via reflection in Scala 2.10?
    primarykey
    data
    text
    <p>Using type tags, I'm able to <em>see</em> the parameters of some type:</p> <pre><code>scala&gt; import scala.reflect.runtime.universe._ import scala.reflect.runtime.universe._ scala&gt; typeOf[List[Int]] res0: reflect.runtime.universe.Type = List[Int] </code></pre> <p>But I just can't quite figure out how to programmatically get that "Int" out of there, in a general way. </p> <p>(I've been wandering around in REPL for an hour now, trying permutations on Type, to see what I can obtain from it... I get a lot of things which indicate this is a "List", but good luck on finding that "Int"! And I don't really want to resort to parsing the toString() output...)</p> <p>Daniel Sobral has an excellent (as usual) quick overview <a href="http://dcsobral.blogspot.fr/2012/07/json-serialization-with-reflection-in.html">here</a>, in which he gets tantalizingly close to what I'm looking for, but (apparently) only if you happen to know, for that particular class, some specific method whose type can be interrogated:</p> <pre><code>scala&gt; res0.member(newTermName("head")) res1: reflect.runtime.universe.Symbol = method head scala&gt; res1.typeSignatureIn(res0) res2: reflect.runtime.universe.Type = =&gt; Int </code></pre> <p>But I'm hoping for something more general, which doesn't involve rooting around in the list of declared methods and hoping that one of them will capture (and thus divulge) the tag's current type information somewhere.</p> <p>If Scala can so easily <em>print</em> "List[Int]", why on earth is it so hard to discover that "Int" part of that -- without resorting to string pattern matching? Or am I just missing something really, really obvious?</p> <pre><code>scala&gt; res0.typeSymbol.asInstanceOf[ClassSymbol].typeParams res12: List[reflect.runtime.universe.Symbol] = List(type A) scala&gt; res12.head.typeSignatureIn(res0) res13: reflect.runtime.universe.Type = </code></pre> <p>Grr...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload