Does Scala have an equivalent to Haskell's Prelude.read?
In Haskell, I can write read "(1,2)"
and get back the tuple (1,2)
. Is there any way to do this in 开发者_StackOverflow中文版Scala? I guess what I'm looking for is access to the parser in the scala
interpreter.
I've you tried to poke around in scala.tools.nsc ?
Is something like that enough for you needs (or, at least, a good start point) ?
scala> val interpreter = new tools.nsc.Interpreter
interpreter: scala.tools.nsc.Interpreter = scala.tools.nsc.Interpreter@522c5afb
scala> interpreter interpret "(3, 5)"
res0: (Int, Int) = (3,5)
res139: scala.tools.nsc.InterpreterResults.Result = Success
scala> interpreter interpret "1 to 10 toList"
res1: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
res140: scala.tools.nsc.InterpreterResults.Result = Success
[Edit: it seems that tools.nsc.Interpreter is deprecated. There is now a tools.nsc.interpreter package]
You may be interested in the Scala compiler API. You probably need to compile the source and run it. This is AFAIK how it is done in the Scala interpreter.
Remember these issues:
- It can be slow.
- Ït can be a bottleneck in multithreading applications. Loading a class AFAIK requires a synchronization (because of JIT etc.).
- It can be insecure. You can be interested in setting JVM security restrictions.
There is an info about Scala compiler (as in this thread), but it can be outdated: If you need a verbose info, you will probably have to download the source and generate scaladoc.
I don't your motivation to use it, but you can be also interested in JSR 223: Scripting for the Java™ Platform API, if you don't need Scala.
If you want loading of data structures only, you should consider another ways, e.g. Lift JSON library that you can download from Maven or directly download. The library allows you to serialize/deserialize case classes.
精彩评论