2

Twitter util library provides a nice utility for how to evaluate Scala code at runtime, for example:

val eval    = new com.twitter.util.Eval()
val example = eval.apply("""
    case class E() { 
        def one(): Int = 1
    }
    (new E).one()
""").asInstanceOf[Int]
// example: Int = 1

But is it possible to evaluate code that doesn't return anything (returns status true/false - complied/failed) and then start using classes defined within evaluated part, for example:

val eval = new com.twitter.util.Eval()

eval.{_MAGIC_METHOD_}("""
    case class E() { 
        def one(): Int = 1
    }
""")

val one = (new E).one(); // and this one will be -> one: Int = 1

So I'm curious about {_MAGIC_METHOD_} part, is it possible to do this with some library? Is it possible with Twitter utils? Some other util library? Scala compiler (Scala Compiler - http://mvnrepository.com/artifact/org.scala-lang/scala-compiler)?

Thanks in advance for your help and any suggestions.

Dmitry F
  • 1,650
  • 1
  • 15
  • 20
  • 2
    No. The problem is that you need your code to type-check before it runs, and at the type-checking phase you don't have any `E` definition to type-check against. Also, note that the twitter util library provides nothing too special and leaves all the heavy lifting to the scala compiler and scala reflection libraries. – Alec Sep 08 '16 at 04:08
  • 1
    You can use the `toolbox` from your `runtimeuniverse` to run the code which will give you a `ClassTag` then you use add it with the other components of reflection API. – sarveshseri Sep 08 '16 at 05:25

0 Answers0