bootvue
V2EX  ›  Kotlin

kotlin 表达式引擎

By bootvue at 2022 年 7 月 27 日 · 4830 次点击
字符串表达式 "s1 + ( s2 - s3 )" 集合 s1 s2 s3

kotlin 中怎么让预定义的字符串作为表达式执行 实现类似 js 中 eval ( "表达式" )的效果 执行完返回集合类型的结果
4 条回复  •  2022-07-27 16:33:24 +08:00
U2FSDGVK
   1
U2FSDGVK  
   2022 年 7 月 27 日
这个问题我也查过一些,最后找到的是用 kotlin-script 运行字符串
参考:
https://stackoverflow.com/questions/56384889/run-kotlin-stored-as-a-string-is-giving-a-runtime-error
https://stackoverflow.com/questions/49416321/kotlin-dynamically-compile-a-class-from-source-code-at-runtime
实际用起来 kotlin-script 编译挺慢的
Belmode
   3
Belmode  
   2022 年 7 月 27 日
让字符串表达式生成临时 kts 文件,然后再用 kotlin 调用外部命令执行这个 kts ,读取返回结果。
yazinnnn
   4
yazinnnn  
   2022 年 7 月 27 日
https://github.com/Kotlin/kotlin-script-examples/blob/master/jvm/jsr223/jsr223.md

resource/META-INF/services/javax.script.ScriptEngineFactory 中写入
kotlin.script.experimental.jsr223.KotlinJsr223DefaultScriptEngineFactory

https://gist.github.com/yazinnnn/9c7de3320c63f3f5bd5be2df6cc05665

不知道你出于啥目的有这个需求, 如果只是学习的话, 不如直接启动一个 repl
© 2026 V2EX · 40ms · 3.9.8.5