Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala.tools.nsc.Interpreter -- How to execute interpreter statements so that the results are defined in the global scope? (Scala 2.7.7final)

Tags:

scala

I'm experimenting with interpreting strings in Scala to define classes and methods. I used the example from http://scala-programming-language.1934581.n4.nabble.com/Compiling-a-Scala-Snippet-at-run-time-td2000704.html in the following code:

import scala.tools.nsc.{Interpreter,Settings}
var i = new Interpreter(new Settings(str => println(str)))
i.interpret("class Test { def hello = \"Hello World\"}")

It works, but somehow the intepretation results are not happening at the global namespace:

new Test # => <console>:5: error: not found: type Test

Therefore: How to execute interpreter statements so that the results are defined in the global scope? I'm using scala2.7.7final currently, and can't change the interpreter to 2.8.

Thanks for your help

Matthias

like image 858
Matthias Guenther Avatar asked Mar 18 '11 06:03

Matthias Guenther


2 Answers

I think that when you take the step from interpreter to the running application you don't get away from using reflection:

scala> var res = Array[AnyRef](null)
scala> i.bind("result", "Array[AnyRef]", res)
scala> i.interpret("result(0) = new Test")
scala> res
res11: Array[AnyRef] = Array(Test@2a871dcc)

You can still get hold of the class-object and instantiate yourself:

scala> i.interpret("result(0) = classOf[Test]")                            
scala> res(0).asInstanceOf[Class[_]].getConstructors()(0).newInstance()
res24: Any = Test@28bc917c
like image 180
thoredge Avatar answered Nov 08 '22 00:11

thoredge


You can't, because Scala cannot known statically, at compile time, that a class Test will be created by a run-time call.

like image 20
Daniel C. Sobral Avatar answered Nov 07 '22 22:11

Daniel C. Sobral