2
votes

I am trying to use the IMain method from scala's interpreter to run a function that has been converted into a string. However I am unable to import user created classes into the interpreter.

For example, you can easily import classes from the scala database eg:

val m = new IMain()
m.interpret("import scala.math.sin")
m.interpret("sin(10)")

And this import will remain for as long as the interpreter is running. However I haven't been able to find a way to import classes and objects which I have created (or any private library):

m.interpret("import sounder.Sounder.play"
m.interpret("play(t=>50*sin(2*Pi*t*400),0,10")

(play is a method that plays a sound out through the computer's soundcard)

I have tried using all of the methods within interpreter but none seem to work. The only solution I have come up with is to convert the class file into a single line of with ; separating each line and running that through the interpret, but even that is having issues preventing it from compiling.

Is there a method which will allow for inputs into the interpreter, alternatively is there another process that will allow for a string to be processed by the scala interpreter.

Thanks for any help, I am running Scala 2.9.2 on a Windows 7 computer.

1
Ended up not using IMain at all, as the given solution by 0__ wouldn't work. Instead I created a class which would use pattern matching to determine the type of function being used. Not as effective, or as efficient but was best solution I could find. - user1917645

1 Answers

0
votes

Have you tried the following:

val m = new IMain() {
   override protected def parentClassLoader = sounder.Sounder.getClassLoader
}

In Scala 2.10 you can do:

val s = new tools.nsc.Settings()
s.embeddedDefaults[sounder.Sounder]
val m = new IMain(s)

You may run into trouble if you launch your programme via sbt run. The manual will tell you that you need to add fork in run := true to your build.sbt, but that doesn't help with custom libraries I'm afraid.