0

シナリオを単純化するために、Some[String] または Some[Int] または None である Type オブジェクトがあります。その Type オブジェクトを取得して、どうにかして Type パラメータを別のオブジェクトに取得できますか?

例えば

scala>  import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> val tt = typeTag[Some[String]]
tt: reflect.runtime.universe.TypeTag[Some[String]] = TypeTag[scala.Some[String]]

scala> val tpe = tt.tpe
tpe: reflect.runtime.universe.Type = scala.Some[String]

したがって、あなたの Type of Some[String] があります。そこからパラメータの型を Type オブジェクトに取得するにはどうすればよいですか?

4

1 に答える 1

1

リンクされた回答TypeRefのように、エクストラクタを使用できます。

import reflect.runtime.universe._

val tpe = typeOf[Some[String]] // same as typeTag[Some[String]].tpe

// extract type parameters
val TypeRef(_,_, tps) = tpe
// tps has type List[Type]

val innerType = tps.head // <-- here is your type
// innerType: reflect.runtime.universe.Type = String
于 2013-06-20T17:42:59.647 に答える