7

型宣言があれば、型引数を解決することができます。

scala> reflect.runtime.universe.typeOf[List[Int]] match {case x:TypeRef => x.args}
res10: List[reflect.runtime.universe.Type] = List(Int)

ランタイム値の場合、同じメソッドは機能しません。

scala> reflect.runtime.currentMirror.reflect(List(42)).symbol.toType match {case x:TypeRef => x.args}
res11: List[reflect.runtime.universe.Type] = List(B)

反映された値の型消去を克服する方法はありますか?

4

1 に答える 1

6

Scalaを読んで得た TypeTag の知識に基づく例 : TypeTag とは何ですか? あなたの質問に対するコメントでEugene Burmako によって投稿され ました:

import scala.reflect.runtime.universe._

object ScalaApplication {
  def main(args: Array[String]) {
    printType(List(42))
    printType(List("42"))
    printType(List("42", 42))
  }    

  def printType[T : TypeTag](t: T) {
    println(typeOf[T])
  }
}

これにより、次の出力が得られます。

$ scala ScalaApplication.scala 
List[Int]
List[String]
List[Any]

[更新 1:]

ただし、型の参照に割り当てられた型を認識したい場合は、Anyある種の型認識ラッパーを選択する必要がある場合があります。

import scala.reflect.runtime.universe._

object ScalaApplication {
  def main(args: Array[String]) {
    val anyWrapper = new AnyWrapper

    List(1,2,3).foreach { i =>
      i match {
        case 1 => anyWrapper.any = 42
        case 2 => anyWrapper.any = "a string"
        case 3 => anyWrapper.any = true
      }
      print(anyWrapper.any)
      print(" has type ")
      println(anyWrapper.typeOfAny)
    }
  }

  class AnyWrapper {
    private var _any: Any = null
    private var _typeOfAny: Type = null

    def any = _any
    def typeOfAny = _typeOfAny
    def any_=[T: TypeTag](a: T) = {
      _typeOfAny = typeOf[T]
      _any = a
    }

  }
}

これにより、次の出力が得られます。

$ scala ScalaApplication.scala 
42 has type Int
a string has type String
true has type Boolean

ただし、この解決策では、コンパイル時に参照型が不明な場合はまだカバーされていません。

[更新 2:]

型が type の参照に明示的にキャストされている場合、型Anyを復元するために、一致するステートメントで可能なすべての型を列挙する必要がある場合があります。

import scala.reflect.runtime.universe._

object ScalaApplication {
  def main(args: Array[String]) {

    List(1,2,3).foreach { i =>
      val any: Any = i match {
        case 1 => 42.asInstanceOf[Any]
        case 2 => "a string".asInstanceOf[Any]
        case 3 => true.asInstanceOf[Any]
      }
      print(any)
      print(" has type ")
      println(matchType(any))
    }
  }

  def matchType(any: Any) = {
    any match {
      case a: Int => typeOf[Int]
      case a: String => typeOf[String]
      case a: Boolean => typeOf[Boolean]
    }
  }
}

これにより、次の出力が得られます。

$ scala ScalaApplication.scala
42 has type Int
a string has type String
true has type Boolean

ただし、この解決策では、値で受け取る可能性のあるすべての型を知っている (および一覧表示する) 必要がありanyます。

于 2012-09-18T13:07:47.210 に答える