7

I want to run kotlin code as script from java with Java Scripting API similar to this for javascript:

import javax.script.*;
public class EvalScript {
    public static void main(String[] args) throws Exception {
        // create a script engine manager
        ScriptEngineManager factory = new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        engine.eval("print('Hello, World')");
    }
}

or with similar APIs like this.

2
  • I'm sure you could, but why? The point of Kotlin is that it compiles to JVM bytecode. Commented Jul 31, 2016 at 18:09
  • I want to use it for load kotlin Type-Safe Builders dsl or something like this in runtime. Commented Jul 31, 2016 at 18:13

2 Answers 2

10

Yes, it's possible starting from the Kotlin 1.1: http://kotlinlang.org/docs/reference/whatsnew11.html#javaxscript-support

KEEP-75 has an example of the JSR-223 API call:

val engine = ScriptEngineManager().getEngineByExtension("main.kts")!!
engine.eval("""
@file:DependsOn("junit:junit:4.11")

org.junit.Assert.assertTrue(true)

println("Hello, World!")
""")

Configuration below adds Kotlin scripts engine to my Kotlin 1.2 project:

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-script-runtime</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-script-util</artifactId>
            <version>${kotlin.version}</version>
        </dependency>

Update: Starting from Kotlin 1.2.20 kotlin-script-util doesn't depend on kotlin-compiler explicitly (see https://youtrack.jetbrains.com/issue/KT-17561). So one more module should be provided (as of the build file in example project):

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-compiler-embeddable</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
Sign up to request clarification or add additional context in comments.

Comments

4

Kotlin support for the Java Scripting API is planned, but as of version 1.0.3 is not available yet. For the mean time, you can try to use an existing open-source implementation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.