Scala TypeTag 反射返回类型 T [英] Scala TypeTag Reflection returning type T

查看:71
本文介绍了Scala 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 什么都不是.

I would REALLY like to not have the .asInstanceOf[T] if possible (runtime). Is this possible? Removing the asInstanceOf gives me a type of Any, which makes sense, but since we are using reflection and know for sure that I am returning a value of type T, I don't see why we can't have T as a return type, even if we are using reflection at runtime. The code block there without asInstanceOf[T] is never anything but T.

推荐答案

此处不应使用反射.相反,隐式,特别是类型类模式,提供了一个编译时解决方案:

You should not be using reflection here. Instead implicits, specifically the type-class pattern, provide a compile-time solution:

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

这篇关于Scala TypeTag 反射返回类型 T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆