簡體   English   中英

Scala TypeTag反射返回類型T

[英]Scala TypeTag Reflection returning type 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。

您不應該在這里使用反射。 相反,隱式(特別是類型類模式)提供了編譯時解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM