2013-12-21 26 views
3

我正在使用Scala 2.10編寫一個通用值解析器。 輸入是一個字符串,輸出是用戶給出的通用類型。scala中的通用類型解析器2.10

我能想出的唯一事情是

val StringTYPE = classOf[java.lang.String] 

def parseValue[T: ClassTag](str: String): T = { 
    implicitly[ClassTag[T]].runtimeClass match { 
    case java.lang.Integer.TYPE => str.toInt.asInstanceOf[T] 
    case java.lang.Long.TYPE => str.toLong.asInstanceOf[T] 
    case StringTYPE => str.asInstanceOf[T] 
    case _ => throw new Exception("Unknown type") 
    } 
} 

但似乎非常繁瑣和複雜,所以我不知道有沒有什麼簡單的方法來做到這一點?

回答

8

在編譯時條件下使用運行時錯誤似乎很奇怪。你有沒有考慮過類型班?

trait Readable[T] { 
    def read(str: String): T 
} 

object Readable { 


    implicit object IntIsReadable extends Readable[Int] { 
    def read(str: String): Int = str.toInt 
    } 

    // ... provide similar objects for any types that can be "read" ... 
    // if possible, inside object Readable 
    // or inside the companion object of the type you want to make readable. 
    // Otherwise, ensure that the implicit is in scope when calling Read 
} 


def readValue[T: Readable](str: String): T = implicitly[Readable[T]].read(str) 
0

該解決方案由Aaron給出,正確的方法是類型類。

只是對您的版本提出小的改進(但不要這樣做),您可以直接使用ClassTag進行檢查。此外,命名隱式參數可能比隱式返回更容易:

def parseValue[T](str: String)(implicit tag: ClassTag[T]): T = { 
    if(tag == ClassTag.Int) str.toInt.asInstanceOf[T] 
    else if(tag == ClassTag.Long) ... 
    else if (tag == ClassTag(classOf[String]) … 
    else ??? 
}