scala as scripting language [duplicate]

2019-01-27 17:31发布

问题:

Possible Duplicate:
“eval” in Scala

I know scala is a compiled language, but I do also know that I can dynamically load classes into the jvm, and I can call the scala compiler at runtime, last but not least I do also have an awesome repl, so having scala as a scripting language should be possible.

so there are some tasks I need to get to run:

simple interpret:

val src = """ println("Hello World") """
interpret(src)

call external functions:

object A{
    def foo = 
        println("Hello World")
}

val src = """ A.foo """
interpret(src)

implement functionality:

trait T{
    def foo:String
}

val src = """ class A extends T{ def foo = "Hello World" } """
interpret(src)
val t = loadClassAndCreatInstance.asInstanceOf[T]
println(t.foo)

it would be great to get a solution to all my problems.

回答1:

somehow I already found out how to use scala as scripting language but I still have a problem with the classLoader

object O{
  def foo = println("Hello World in object O")
}

trait T{
  def foo:String
}

object MyInterpreter extends App{
  val srcA = 
  """ 
  println("Hello World from srcA") 
  """

  val srcB = """ O.foo """

  val srcC = """ 
  class A extends T{ 
    def foo = "Hello World from srcC"
    override def toString = "this is A in a src"
  }
  """


  val out = System.out
  val flusher = new java.io.PrintWriter(out)

  val interpreter = {
  val settings = new import scala.tools.nsc.GenericRunnerSettings( println _ )
  new scala.tools.nsc.interpreter.IMain(settings, flusher)
  }

  interpreter.interpret(srcA)
  interpreter.interpret(srcB)
  interpreter.compileString(srcC)

  val classA = interpreter.classLoader.findClass("A")

  println(classA)

  val constructors = classA.getDeclaredConstructors
  val myinstance = constructors(0).newInstance()

  println(myinstance)

  //this still throws an classCastException
  myinstance.asInstanceOf[T].foo 
  //but everything else works
}


回答2:

See my answer here: "eval" in Scala

(I assume you are already aware of scala interactive mode, and how to write executable scripts with a Scala-compatible shebang #! line.)