Multi-file Programs
Let’s consider a more complex version of “Hello World!”, split across two files of source code.
-
In the
tasks/task1_2subdirectory of your repository, create a fileHello.ktcontaining this code:fun main(args: Array<String>) { if (args.isNotEmpty()) { println(greetingFor(args[0])) } else { println(greetingFor("World")) } } -
Now create a new file named
Greet.kt, containing the following:fun greetingFor(target: String): String { val greeting = setOf("Hello", "Hi", "G'day").random() return "$greeting $target!" }Make sure that this is in the same directory as
Hello.kt. (This should be thetasks/task1_2subdirectory of your repository.) -
In a terminal window, go to
tasks/task1_2and compile the program withkotlinc Hello.kt Greet.ktThe compiler will generate a separate file of bytecode for each of the source files. If you list the directory contents, you should see
HelloKt.classandGreetKt.class. -
Try running the program, with and without a command line argument:
kotlin HelloKt Joe kotlin HelloKtNotice that there is no need to specify
GreetKthere. The Java Virtual Machine (JVM) is able to find and load all of the bytecode needed to run the application. All you need to do is specify the entry point, i.e., the place where themain()function can be found.Remove the two
.classfiles before proceeding further, e.g., withrm HelloKt.class GreetKt.class -
It’s hard to manage an application whose code is spread across multiple files of bytecode, so the Kotlin compiler allows us to bundle the code together in a single JAR file.
Try this now:
kotlinc -d hello.jar Hello.kt Greet.ktCheck the size of this JAR file, then list its contents, using the two commands below. (Use
dirinstead ofls -lif you are trying this on Windows.)ls -l hello.jar jar -tf hello.jar -
Run the application in
hello.jarwith this command:kotlin -cp hello.jar HelloKtAs before, you can add a command line argument to this if you wish.
Notice the need for the
-cpoption here. This adjusts the JVM’s classpath so that it includeshello.jar, thus ensuring thathello.jarwill be searched to find the bytecode of the application. -
It is also possible to bundle the Kotlin runtime library with a JAR file. Try this now:
kotlinc -include-runtime -d hello.jar Hello.kt Greet.ktCheck the size and contents of
hello.jaragain. You’ll see that it is now very much larger than before. Although this big increase in size is annoying for such a simple program, the advantage is that the JAR file is now portable to a system that doesn’t have Kotlin’s development tools installed. The only requirement is that a JVM be available on that system. -
Try running the application directly on the JVM with this command:
java -jar hello.jar