使用twitter Eval库:https://twitter.github.io/util/docs/index.html#com.twitter.util.Eval
val i: Int = new com.twitter.util.Eval()("1 + 1")
println(i)
打印2
val fun = new com.twitter.util.Eval()("object obj { def fun = {println(\"fun\")}; fun() }")
println(i)
导致异常:
Exception in thread "main" com.twitter.util.Eval$CompilerException: Compiler exception error: line 1: Unit does not take parameters
object obj { def fun = {println("fun")}; fun() }
^
at com.twitter.util.Eval$StringCompiler.apply(Eval.scala:585)
at com.twitter.util.Eval$StringCompiler$$anonfun$apply$2.apply(Eval.scala:596)
at com.twitter.util.Eval$StringCompiler$$anonfun$apply$2.apply(Eval.scala:595)
at scala.Option.getOrElse(Option.scala:121)
at com.twitter.util.Eval$StringCompiler.apply(Eval.scala:595)
at com.twitter.util.Eval.applyProcessed(Eval.scala:203)
at com.twitter.util.Eval.applyProcessed(Eval.scala:196)
at com.twitter.util.Eval.apply(Eval.scala:142)
at gen.Compiler$.delayedEndpoint$gen$Compiler$1(Compiler.scala:8)
at gen.Compiler$delayedInit$body.apply(Compiler.scala:4)
at scala.Function0$class.apply$mcV$sp(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:76)
at scala.App$$anonfun$main$1.apply(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:381)
at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35)
at scala.App$class.main(App.scala:76)
at gen.Compiler$.main(Compiler.scala:4)
at gen.Compiler.main(Compiler.scala)
可以使用twitter Eval库来调用Eval库评估的函数吗?
Eval版本:
<dependency>
<groupId>com.twitter</groupId>
<artifactId>util-eval_2.11</artifactId>
<version>6.30.0</version>
</dependency>
答案 0 :(得分:2)
看起来你可以,但我只是在object
范围之外成功完成了。它可能或可能符合您的需求:
val fun = new com.twitter.util.Eval().apply[Unit]("""
object obj {
def fun() = {
println("fun")
}
}
obj.fun()
"""
)
您还必须指定已计算表达式的类型,因此为了做到这一点,您必须显式调用apply
函数,该函数采用类型参数。
更新:您可以从eval块返回Unit
,而不是Function0[Unit]
,并将其分配给val fun
:
scala> val fun = new com.twitter.util.Eval().apply[Function0[Unit]]("""
object obj {
def fun() = {
println("printing fun")
}
}
obj.fun()
obj.fun _
"""
)
printing fun
fun: () => Unit = <function0>
scala> fun()
printing fun