Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create complex data from Strings in Scala

Tags:

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

like image 431
Joe Lehmann Avatar asked Apr 28 '26 06:04

Joe Lehmann


2 Answers

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

like image 169
Tomer Gabel Avatar answered Apr 30 '26 21:04

Tomer Gabel


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.

like image 33
Kim Stebel Avatar answered Apr 30 '26 20:04

Kim Stebel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!