Compile to Bytecode and Run
We'll cover the following...
Let’s first create a small Hello World program in Kotlin. Using your favorite text editor create a file named Hello.kt
, like so:
fun main() = println("Hello World")
Don’t worry about the syntax in the code at this time; let’s keep our focus on getting the code to run. We’ll discuss the language syntax and semantics in following chapters. You may specify the parameter for the main()
function if you like, but starting with Kotlin 1.3
, it’s optional. If you’re using a version prior to 1.3
, then you’ll need to add the parameter, like so:
fun main(args: Array<String>).
Running on the command line
To compile and run the code from the command line, first execute the following command:
kotlinc-jvm Hello.kt -d Hello.jar
This command will compile the code in the file Hello.kt
into Java bytecode and
place that into the Hello.jar file.
Once the jar file is created, run the program using the java tool, like so:
java -classpath Hello.jar HelloKt
Since the file Hello.kt
contains only the main function and not a class, the Kotlin compiler, kotlinc-jvm
, automatically creates a class named after the file name, without the .kt
extension, but adds a Kt
suffix.
Here’s the output of running the code:
Hello World
Instead of specifying the classpath command-line option, you may also use the jar option to run the code. That’s because, upon finding the main()
function, the Kotlin compiler decided to add the Main-Class manifest attribute to the jar file. Go ahead and try out the following command on the Hello.jar
file: ...