动态评估Kotlin中的模板化字符串 [英] Dynamically evaluating templated Strings in Kotlin

查看:178
本文介绍了动态评估Kotlin中的模板化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下Kotlin代码:

Suppose that I have the following piece of Kotlin code:

fun main(args: Array<String>) {
    val a = "test"
    println(args.first())
}

如果我传递参数 $ a ,则输出将为 $ a 。据了解,Kotlin通过生成编译输出的代码,大概使用StringBuilder来处理String模板。有没有一些方法可以评估与当前上下文中的模板相关的源代码中的字符串?字符串模板非常有用,能够评估来自动态上下文(例如配置文件)的表达式,但是据我所知,这不能完成。

If I pass in an argument $a, the output is going to be $a. As I understand it Kotlin takes care of String templates by generating the code for the output on compilation, presumably using a StringBuilder. Is there some way to evaluate Strings that aren't in the source code with regards to templates in their current context? String templates are very useful and it'd be great to be capable of evaluating expressions that come from a dynamic context, such as configuration files, but as far as I can tell this can't be done.

缺少这一点,对这个方法是什么?调用脚本引擎?

Lacking that, what would be a good approach towards this? Invoking a scripting engine?

推荐答案

如果您需要以这种方式评估任意表达式,那么是的,您需要一个脚本引擎。 Kotlin可以使用 JSR 223 实现,请参阅示例这里( kotlin-jsr223 - * projects)

If you need to evaluate arbitrary expressions in this way, then yes, you need a scripting engine. Kotlin has a JSR 223 implementation that you can use, see the examples here (the kotlin-jsr223-* projects).

这是一个基本的用法示例:

Here is a basic usage example:

val engine = ScriptEngineManager().getEngineByExtension("kts")!!
engine.eval("val x = 3")
val res = engine.eval("x + 2")
Assert.assertEquals(5, res)

代码取自 KotlinJsr223ScriptEngineIT .kt ,并记住通过 META-INF 配置服务

这篇关于动态评估Kotlin中的模板化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆