import javax.script.*
fun main () {
val engine = ScriptEngineManager().getEngineByExtension("kts")!!
println (engine.eval("2 + 3"))
}
How do I have to compile and run it on the command line without the use of any fancy build tools or IDEs? Which JARs are required to run it directly with Java? I tried all, but it does not seem to be enough:
java -cp .:$(echo ../kotlinc/lib/*.jar | tr ' ' ':'):livetribe-jsr223.jar HelloKt
ScriptEngineManager providers.next(): javax.script.ScriptEngineFactory: Provider org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory not found
Exception in thread "main" java.lang.NullPointerException
at HelloKt.main(hello.kt:4)
at HelloKt.main(hello.kt)
The error is self-explanatory. You did not load a JSR223 provider for kotlin. It does not come out of the box for kotlin like it does for groovy. You need to at least add the engine to the build (not only this artifact but all its dependencies as well).
By the way, you can keep using groovy as a scripting language, it works perfectly fine inside kotlin and the size of groovy jar is much smaller, then the size of kotlin compiler.
And in the folder src/main/resources/META-INF/services/ I create a file called javax.script.ScriptEngineFactory with the following content: org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngineFactory.
Agreed, it works and is decently easy to set up (despite lacking documentation). I couldn’t get it to work with shadow fatjars so I switched to the non jsr223 way.