STRUCTURE:
1.Main.kt file
import kotlinx.coroutines.*
fun main(args: Array<String>) {
GlobalScope.launch { // launch a new coroutine in background and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello,") // main thread continues while coroutine is delayed
Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}
2. kotlinx-coroutines-core-1.3.0-M1.jar
https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-core/1.3.0-M1
COMPILE COMMAND:
kotlinc Main.kt -cp kotlinx-coroutines-core-1.3.0-M1.jar -include-runtime -d program.jar
output: program.jar
RUN:
java -jar program.jar
EXCEPTION:
Exception in thread "main" java.lang.NoClassDefFoundError: kotlinx/coroutines/GlobalScope
at MainKt.main(Main.kt:10)
Caused by: java.lang.ClassNotFoundException: kotlinx.coroutines.GlobalScope
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
How can I fix this?
You should also specify additional classpath libraries when you run it:
java -cp kotlinx-coroutines-core-1.3.0-M1.jar:program.jar MainKt
@elizarov thnx it works!
here is my kc command to run kotlin faster
#!/usr/local/bin/bash
function kc {
file=$1
lib=$2
arr=(${file//./ })
name=${arr[0]}
sufix=${arr[1]}
out="${name}.jar"
class="${name^}${sufix^}"
# echo $file
# echo $lib
# echo $out
# echo $class
if [ "$lib" != "" ];then
echo "kotlinc $file -cp $lib -include-runtime -d $out ..."
kotlinc $file -cp $lib -include-runtime -d $out
echo "java -cp $lib:$out $class ..."
java -cp $lib:$out $class
else
echo "kotlinc $file -include-runtime -d $out ..."
kotlinc $file -include-runtime -d $out
echo "java -jar $out ..."
java -jar $out
fi
}
kc $1 $2
make sure your bash version is up to 5.0
@zyfyy 's script did not work for me.
by chance i stumbled up a post that gave me the right hint: i need to add @file:JvmName("MainKt") at the top of main.kt
then it worked!
thanks for sharing.
Most helpful comment
You should also specify additional classpath libraries when you run it: