JSR 223 Scripting in Kotlin 1.8.0

I try to perform JSR223 Scripting in Kotlin 1.8.0 with

kotlinEngine = new ScriptEngineManager().getEngineByName(“kotlin”);

However, when I try to evaluate expressions, I get this error:

   Exception in thread "main" 

java.lang.NoSuchMethodError: ‘void kotlin.script.experimental.jvmhost.jsr223.KotlinJsr223ScriptEngineImpl.(javax.script.ScriptEngineFactory, kotlin.script.experimental.api.ScriptCompilationConfiguration, kotlin.script.experimental.api.ScriptEvaluationConfiguration)’

at kotlin.script.experimental.jsr223.KotlinJsr223DefaultScriptEngineFactory.getScriptEngine(KotlinJsr223DefaultScriptEngineFactory.kt:45)

at java.scripting/javax.script.ScriptEngineManager.lambda$getEngineBy$2(ScriptEngineManager.java:237)

at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)

at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.tryAdvance(StreamSpliterators.java:300)

at java.base/java.util.stream.Streams$ConcatSpliterator.tryAdvance(Streams.java:723)

at java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:129)

at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:527)

at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:513)

at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)

at java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:150)

at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)

at java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:647)

at java.scripting/javax.script.ScriptEngineManager.getEngineBy(ScriptEngineManager.java:246)

at java.scripting/javax.script.ScriptEngineManager.getEngineByName(ScriptEngineManager.java:185)

at kotlinLabGlobal.Interpreter.GlobalValues.initKotlinEngine(GlobalValues.java:460)

at kotlinLabExec.kotlinLab.kotlinLab.<init>(kotlinLab.java:123)

at kotlinLabExec.kotlinLab.kotlinLab.main(kotlinLab.java:240)

What happens?

please provide the evaluation script

Here is the initKotlinEngine() method, that inits the Kotlin Engine, it worked well on old Kotlin versions, now the engine also is created but fails on evaluating expressions:

public static void initKotlinEngine() {

var args = new String[1];
args[0]=“”;
// KotlinShell.main(args);
// initialize the classpath using the CLASSPATH manifest entry of the jar file
List clp = PathUtils.INSTANCE.classpathFromJar(new File(GlobalValues.jarFilePath));

    StringBuilder sb = new StringBuilder();
    clp.stream().forEach(x ->
    {
        var file = x.getPath();
        System.out.println(file);
        if (GlobalValues.hostIsUnix)
            sb.append(file + ":");
        else  // Windows
            sb.append(file + ";");

    });

    String extraJarsForKotlinClasspathFolder = GlobalValues.kotlinLabLibPath.replace("lib", "extraJarsForKotlinClasspath");

    File[] toolboxesFolderFiles = (new java.io.File(extraJarsForKotlinClasspathFolder)).listFiles();  // get the list of files at the default toolboxes folder
    if (toolboxesFolderFiles != null) {  // extraJarsForKotlinClasspath folder not empty
        int numFiles = toolboxesFolderFiles.length;
        for (int f = 0; f < numFiles; f++) {
            String currentFileName = toolboxesFolderFiles[f].getAbsolutePath();

            if (currentFileName.endsWith(".jar")) {

                if (GlobalValues.hostIsUnix)
                    sb.append(currentFileName + ":");
                else   // Windows
                    sb.append(currentFileName + ";");
            }  // endsWith("jar")
        }   // for all files of then extraJarsForKotlinsFClasspath folder
    }   // extraJarsForKotlinClasspath folder not empty

    System.setProperty("kotlin.script.classpath", sb.toString());

var cf = new org.jetbrains.kotlin.config.CompilerConfiguration();
System.out.println(“compiler configuration =”+ org.jetbrains.kotlin.config.CompilerConfiguration.class.getName());
System.out.println("compiler version = "+org.jetbrains.kotlin.config.KotlinCompilerVersion.getVersion());
kotlinEngine = new ScriptEngineManager().getEngineByName(“kotlin”);
// new KotlinJsr223DefaultScriptEngineFactory().getScriptEngine();

    if (kotlinEngine == null) {
        JOptionPane.showMessageDialog(null, "Kotlin engine is null!!");
        //System.exit(1);
    }


    if (kotlinEngine != null) {

        try {
            for (String str : GlobalValues.kotlinGlobalImports) {
                System.out.println("evaluating: " + str);

                kotlinEngine.eval(str);

            }

            for (String str : GlobalValues.additionalKotlinImports) {
                System.out.println("evaluating kotlin: " + str);

                kotlinEngine.eval(str);

            }

        } catch (ScriptException e) {
            //e.printStackTrace();
        }
    }

}

Please use this code in kotlin jvm

build.gradle.kts

plugins {
    id("org.jetbrains.kotlin.jvm") version "1.8.0"
    application
}

repositories {
    mavenCentral()
}

dependencies {
    runtimeOnly("org.jetbrains.kotlin:kotlin-main-kts:1.8.0")
    runtimeOnly("org.jetbrains.kotlin:kotlin-scripting-jsr223:1.8.0")
}

application {
    mainClass.set("com.zigma.AppKt")
}

settings.gradle.kts

pluginManagement {
    repositories {
        mavenCentral()
        mavenLocal()
    }
}

App.kt

package com.zigma

import javax.script.ScriptEngineManager

class App {
    val greeting: String
        get() {
            return "Hello World!"
        }
}

fun main() {
    println(App().greeting)
	val engine = ScriptEngineManager().getEngineByExtension("main.kts")!!
    val res1 = engine.eval("""
		val x = 3
        x
    """)
	println(res1)
}

Execute ./gradlew run you will get this output which numeric value “3”

Output

> Task :compileJava NO-SOURCE
> Task :classes UP-TO-DATE
> Task :jar
> Task :inspectClassesForKotlinIC

> Task :run
Hello World!
3

BUILD SUCCESSFUL in 4s

in java please use the below code, the name of the engine is kts

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

in main method

ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("kts");
Integer x = (Integer) engine.eval(
			  "val x = 3\n" +
			  "x"
		   );
System.out.println(x);

if you are using maven please use the below dependencies

<dependency>
	<groupId>org.jetbrains.kotlin</groupId>
	<artifactId>kotlin-scripting-jsr223</artifactId>
	<version>1.8.0</version>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>org.jetbrains.kotlin</groupId>
	<artifactId>kotlin-main-kts</artifactId>
	<version>1.8.0</version>
	<scope>runtime</scope>
</dependency>

I reconfigured jar files, however now Script Engine fails again to initialize and outputs the message

ERROR class org.jetbrains.kotlin.parcelize.ParcelizeComponentRegistrar cannot be cast to class org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar (org.jetbrains.kotlin.parcelize.ParcelizeComponentRegistrar and org.jetbrain

Unfortunately, again it does not work. I used this code:

package kotlinLabExec.kotlinLab

import javax.script.ScriptEngineManager

object testScript {
@JvmStatic
fun main(args: Array) {
try {
//ScriptEngine engine = new ScriptEngineManager().getEngineByExtension(“kts”);
val engine = ScriptEngineManager().getEngineByName(“kotlin”)
val x = engine.eval(
“”"
val x = 3
x
“”".trimIndent()
) as Int
println(x)
} catch (e: Exception) {
e.printStackTrace()
}
}
}

and I get as output:

ERROR @NotNull method org/jetbrains/kotlin/config/CompilerConfiguration.getNotNull must not return null: java.lang.IllegalStateException: @NotNull method org/jetbrains/kotlin/config/CompilerConfiguration.getNotNull must not return null
at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.asJsr223EvalResult(KotlinJsr223JvmScriptEngineBase.kt:104)
at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.compileAndEval(KotlinJsr223JvmScriptEngineBase.kt:63)
at kotlin.script.experimental.jvmhost.jsr223.KotlinJsr223ScriptEngineImpl.compileAndEval(KotlinJsr223ScriptEngineImpl.kt:95)
at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.eval(KotlinJsr223JvmScriptEngineBase.kt:31)
at java.scripting/javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:262)
at kotlinLabExec.kotlinLab.testScript.main(testScript.kt:11)

this means you are having dependencies wrongly in your gradle, clean you gradle with proper version without mixing too many old and new libraries

you can see my gradle, without proper output

Again, it does not work.

My Gradle script is:

val kotlinVersion = “1.8.0”

plugins {

java
application
kotlin("jvm") version "1.8.0"

}java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(16))

}

}

tasks.withType {
val compilerArgs = options.compilerArgs
compilerArgs.addAll(listOf(“–add-modules”, “jdk.incubator.vector”))
}

repositories {
    mavenCentral()
    jcenter()
}


dependencies {

     runtimeOnly("org.jetbrains.kotlin:kotlin-scripting-jsr223:$kotlinVersion")

implementation(“org.jetbrains.kotlin:kotlin-stdlib”)
implementation(“org.jetbrains.kotlin:kotlin-script-runtime:$kotlinVersion”)
implementation(“org.jetbrains.kotlin:kotlin-script-util:$kotlinVersion”)
implementation(“org.jetbrains.kotlin:kotlin-compiler-embeddable:$kotlinVersion”)

    implementation("org.jetbrains.kotlin:kotlin-main-kts:$kotlinVersion")
    implementation("org.jetbrains.kotlin:kotlin-scripting-jsr223:$kotlinVersion")



//    runtimeOnly("org.jetbrains.kotlin:kotlin-main-kts:$kotlinVersion")
   // runtimeOnly("org.jetbrains.kotlin:kotlin-scripting-jsr223:$kotlinVersion")

  //  runtimeOnly("org.jetbrains.kotlin:kotlin-scripting-jsr223:$kotlinVersion")

//implementation(fileTree(“./lib/”) { include (“*.jar”)})

}

application {
mainClassName = “kotlinLabExec.kotlinLab.testScript”
}

sourceSets {
main {
java.srcDir(“src”)
}
}

tasks.register(“uberJar”) {
archiveClassifier.set(“uber”)
from(sourceSets.main.get().output)
dependsOn(configurations.runtimeClasspath)
duplicatesStrategy = DuplicatesStrategy.WARN
from( {
configurations.runtimeClasspath.get().map{ zipTree(it)
}
})
}

var libpathfiles= StringBuilder();
File(“./lib”).walk().forEach { e →
if (e.toString().trim().endsWith(“.jar”))
libpathfiles.append(e.toString().replaceFirst(“./”, “”).trim()).append(" ")

}

var kotlinlibpathfiles= StringBuilder();
File("./libkotlin").walk().forEach {
        e-> if (e.toString().trim().endsWith(".jar"))
    kotlinlibpathfiles.append(e.toString().replaceFirst("./","").trim()).append(" ")

}



var allClassPath = kotlinlibpathfiles.toString().trim()+" "+libpathfiles.toString().trim()

tasks.jar {
baseName = “kotlinLab”

manifest {
      attributes["Class-Path"] = allClassPath.trim()
        attributes["Main-Class"] ="kotlinLabExec.kotlinLab.testScript"    }

}

And my code:

package kotlinLabExec.kotlinLab;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
class testScript {
public static void main(String args) {
try {
//ScriptEngine engine = new ScriptEngineManager().getEngineByExtension(“.kts”);
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension(“main.kts”);

                Object x = engine.eval("val x = 3;");
                
       System.out.println(x);
    } catch ( Exception e) {
        e.printStackTrace();
    }
}

}

I get the following error message:

ERROR @NotNull method org/jetbrains/kotlin/config/CompilerConfiguration.getNotNull must not return null: java.lang.IllegalStateException: @NotNull method org/jetbrains/kotlin/config/CompilerConfiguration.getNotNull must not return null
at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.asJsr223EvalResult(KotlinJsr223JvmScriptEngineBase.kt:104)
at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.compileAndEval(KotlinJsr223JvmScriptEngineBase.kt:63)
at kotlin.script.experimental.jvmhost.jsr223.KotlinJsr223ScriptEngineImpl.compileAndEval(KotlinJsr223ScriptEngineImpl.kt:95)
at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.eval(KotlinJsr223JvmScriptEngineBase.kt:31)
at java.scripting/javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:262)
at kotlinLabExec.kotlinLab.testScript.main(testScript.java:12)

the issue is with all the configurations you do, I am not doing those, my gradle is clean it does not have any source set and uberJar, I think that is where the error comes from

you can checkout my code, it is written kotlin, same can be done in java