开发者

Create complex data from Strings in Scala

I have defined a number of case classes such as

  abstract class Foo
  case class Bar(s: String) extends Foo
  case class Baz(f: Foo) extends Foo
  case class FooBar(l: Foo, r:Foo)

that allow me to create complex data, e.g.,

  val x = FooBar(Bar("1"), Baz(Bar("2")))

I want to read these type of data from a string, such as

  val x = what_to_do_here?("FooBar(Bar("1"), Baz(Bar("2")))")

In a dynamic language I would just call eval. (Edit: I rea开发者_开发知识库lly do not want to call something like eval in scala)

The solution I came up with in scala was to write a parser. Is there a simpler way to do that?


You are assuming that there's a construct that's symmetric with toString. I'm pretty sure there isn't one.

Since what you're discussing is a classic serialization/deserialization scenario, you may want to look into a serialization library (one possibility that comes to mind is lift-json, which with I've had considerable success, but there are certainly alternatives). Either that, or I've completely missed your usage scenario :-)


You can use the scala interpreter to write your own eval function. Since the interpreter is actually a compiler, I don't think this will be very fast.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜