Scala 2.10中的通用类型解析器(Generic type parser in scala 2.10)

编程入门 行业动态 更新时间:2024-10-21 16:06:20
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)

更多推荐

本文发布于:2023-08-03 12:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1389319.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   Scala   Generic   scala   parser

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!