简体   繁体   中英

Scala TypeTag Reflection returning type T

I currently have this:

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()

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)
}

Which can be used like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM