【问题标题】:Scala TypeTag Reflection returning type TScala TypeTag 反射返回类型 T
【发布时间】:2014-06-16 14:05:06
【问题描述】:
我目前有这个:
def stringToOtherType[T: TypeTag](str: String): T = {
if (typeOf[T] =:= typeOf[String])
str.asInstanceOf[T]
else if (typeOf[T] =:= typeOf[Int])
str.toInt.asInstanceOf[T]
else
throw new IllegalStateException()
如果可能(运行时),我真的很想没有 .asInstanceOf[T]。这可能吗?删除 asInstanceOf 给了我一个 Any 类型,这是有道理的,但是由于我们使用反射并且确定我正在返回 T 类型的值,所以我不明白为什么我们不能将 T 作为返回类型,即使我们在运行时使用反射。没有 asInstanceOf[T] 的代码块就是 T。
【问题讨论】:
标签:
scala
reflection
runtime
compile-time
【解决方案1】:
您不应该在这里使用反射。相反,隐式,特别是类型类模式,提供了一个编译时解决方案:
trait StringConverter[T] {
def convert(str: String): T
}
implicit val stringToString = new StringConverter[String] {
def convert(str: String) = str
}
implicit val stringToInt = new StringConverter[Int] {
def convert(str: String) = str.toInt
}
def stringToOtherType[T: StringConverter](str: String): T = {
implicitly[StringConverter[T]].convert(str)
}
可以这样使用:
scala> stringToOtherType[Int]("5")
res0: Int = 5
scala> stringToOtherType[String]("5")
res1: String = 5
scala> stringToOtherType[Double]("5")
<console>:12: error: could not find implicit value for evidence parameter of type StringConverter[Double]
stringToOtherType[Double]("5")
^