Dynamically evaluating templated Strings in Kotlin

徘徊边缘 提交于 2019-12-09 00:16:15

问题


Suppose that I have the following piece of Kotlin code:

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

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?


回答1:


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)

The code is taken from KotlinJsr223ScriptEngineIT.kt, and remember to configure the service via META-INF




回答2:


Is there some way to evaluate Strings that aren't in the source code with regards to templates in their current context?

There are no template strings in your code sample and a is unused. Am I understanding correctly that you'd like to do something like val evaluated = evalStringTemplate(template, arg1, arg2, ...) with template being a String like "$a" and arg1, arg2, ... being arguments for the template?

If so, there's no Kotlin-specific way to do this, but you can use the Java Formatter class.



来源:https://stackoverflow.com/questions/44009515/dynamically-evaluating-templated-strings-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!