How to run a Kotlin.kt file from command line?


#1

I created a simple Kotlin file, say "hello.kt":

fun main(args:Array<String>) {
  println(“hello, Kotlin!”)
}

How can I run it from the command line?


#2

You can find an answer here http://devnet.jetbrains.com/message/5471284.


#3

https://github.com/andrewoma/kotlin-script


#4

bash> kotlinc/bin/kotlinc-jvm -src Hello.kt -jar hello.jar
bash> java -cp “kotlinc/lib/*:hello.jar” namespace
Hello


#5

Nope - does not work:

I want :

opt> cat hello.kts

package hello

fun main(args: Array) {
println(“Hello World!”)
}

opt> ./kotlinc/bin/kotlinc hello.kts -d hello.jar
hello.kts:3:10: warning: parameter ‘args’ is never used
fun main(args: Array) {
^
opt> java -jar hello.jar
no main manifest attribute, in hello.jar

to work. Doesn’t the novice Kotlin programmer deserve at least that? Somewhere in the sea of “hello worlds” that DO NOT WORK???


#6

Could you please use three backticks (```) before and after code blocks to make code and console sessions more readable? Thanks.

You are compiling a Kotlin script (kts) instead of a Kotlin file (kt). Change the extension, and you will get a JAR containing class hello.HelloKt with a static main, and a manifest marking this class as the main class.

This does not mean that it will work using java -jar hello.jar. It does not work because the Kotlin run-time is not on the class path.

The easiest way is to use the kotlin command. This will add the Kotlin run-time to the class path:

kotlin -cp hello.jar hello.HelloKt

Note that kotlin hello.jar won’t work, because then the run-time is not added to the class path. I have no idea why it is not added in this case though.

If you want to run a Kotlin script directly, you have to put the body of main(...) at the top level, and use kotlinc. See Executing Kotlin scripts in command shell