2014-06-16 30 views
0

我目前有这样的:斯卡拉TypeTag反射返回类型T

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.

回答

3

您不应该在这里使用反射。相反implicits,特别是型类模式,提供了一种编译时溶液:

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") 
            ^