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?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.