Scala 2.10中的通用类型解析器(Generic type parser in 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") } }但它看起来非常冗长和复杂,所以我想知道有没有更简单的方法来做到这一点?
I'm writing a generic value parser using Scala 2.10. The input is a string and the output is a generic type, given by the user.
The only thing I can come up with is
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") } }But it seems very verbose and complicated, so I'm wondering is there any simpler way to do this?
最满意答案
在编译时条件下使用运行时错误似乎很奇怪。 你有没有考虑过类型班?
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)It seems strange to use a run-time error for a compile-time condition. Did you consider a type class?
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)更多推荐
发布评论