Skip to content

Instantly share code, notes, and snippets.

@Jellymath
Last active January 8, 2019 03:53
Show Gist options
  • Save Jellymath/3d730d6ca1b23e59cf76cd29c5c17be8 to your computer and use it in GitHub Desktop.
Save Jellymath/3d730d6ca1b23e59cf76cd29c5c17be8 to your computer and use it in GitHub Desktop.
Answer code for XTANCE
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import kotlin.reflect.KProperty
fun main(args: Array<String>) {
with(ScriptEngineManager().getEngineByExtension("kts")) {
// val x by value { 3 }
// println(x)
// val x = value("x", 3)
// println(x)
eval("val x = 3")
val res2 = eval("\"hello \$x \${x+3}\"")
println(res2)
println(eval(readLine()))
}
}
//doesn't work if you doesn't use as program variable before using in script engine
fun <T: Any> ScriptEngine.value(init: () -> T): Delegate<T> {
return object: Delegate<T> {
val value = { paramName: String ->
val i = init()
this@value.eval("val $paramName = $i")
i
}
lateinit var valueInit: T
override operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
if (!::valueInit.isInitialized) {
valueInit = value(property.name)
}
return valueInit
}
}
}
//variable name duplication
fun <T: Any> ScriptEngine.value(name: String, value: T): T {
eval("val $name = $value")
return value
}
interface Delegate<T: Any> {
operator fun getValue(thisRef: Any?, property: KProperty<*>): T
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment