3

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 really 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?

Joe Lehmann
  • 1,087
  • 5
  • 10

2 Answers2

2

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 :-)

Tomer Gabel
  • 4,104
  • 1
  • 33
  • 37
  • It is indeed a deserialization szenario. However, I cannot control the output of the serialization (because I do not own the code) so using a library isn't an option. I think I'll have to write a little parser – Joe Lehmann Sep 30 '11 at 09:52
  • You could, as you suggest, mock it by integrating the Scala REPL, but I wouldn't recommend it. A simple parser would be much simpler to implement and less error-prone (assuming a reasonable set of classes). – Tomer Gabel Sep 30 '11 at 15:59
1

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.

Kim Stebel
  • 41,826
  • 12
  • 125
  • 142