Scala script in 2.11

后端 未结 1 1284
一生所求
一生所求 2020-12-18 12:23

I have found an example code for a Scala runtime scripting in answer to Generating a class from string and instantiating it in Scala 2.10, however the code seems to be obsol

相关标签:
1条回答
  • 2020-12-18 13:16

    Scala 2.11 adds a JSR-223 scripting engine. It should give you the functionality you are looking for. Just as a reminder, as with all of these sorts of dynamic things, including the example listed in the description above, you will lose type safety. You can see below that the return type is always Object.

    Scala REPL Example:

    scala> import javax.script.ScriptEngineManager
    
    import javax.script.ScriptEngineManager
    
    
    scala> val e = new ScriptEngineManager().getEngineByName("scala")
    
    e: javax.script.ScriptEngine = scala.tools.nsc.interpreter.IMain@566776ad
    
    
    scala> e.put("a", 1)
    
    a: Object = 1
    
    
    scala> e.put("s", "String")
    
    s: Object = String
    
    
    scala> e.eval("""s"a is $a, s is $s"""")
    
    res6: Object = a is 1, s is String`
    

    An addition example as an application running under scala 2.11.6:

    import javax.script.ScriptEngineManager
    
    object EvalTest{
      def main(args: Array[String]){
       val e = new ScriptEngineManager().getEngineByName("scala")
       e.put("a", 1)
       e.put("s", "String")
       println(e.eval("""s"a is $a, s is $s""""))
      }
    }
    

    For this application to work make sure to include the library dependency.

    libraryDependencies +=  "org.scala-lang" % "scala-compiler" % scalaVersion.value
    
    0 讨论(0)
提交回复
热议问题