2. Kotlin From The Command Line

If you want to try these exercises on your own PC, you will need to download the Kotlin compiler. This is a Zip archive. All you need to do is unzip it and then add the bin subdirectory to your path. Note that you will need to have a JVM already installed (version 8 or newer).

2.1. The Kotlin REPL

Kotlin provides a Read-Eval-Print Loop (REPL), similar to that provided for Python. You can use this to experiment with small pieces of Kotlin code.

  1. Run the REPL by entering kotlinc with no arguments. You should see a >>> prompt displayed.

  2. Enter :help to see the small number of REPL commands that are available. Note in particular that :quit is used to exit the REPL and return to the command line.

  3. Try entering the following expressions, one after the other:

    1+2
    "abc" + "def"
    val code = "COMP3222"
    println("Module code is $code")
    Math.sqrt(2.0)
    val data = listOf(-1, 7, 4)
    data.sum()
    
  4. You can also enter code that spans multiple lines. Try the following:

    1
    2
    3
    4
    5
    var x = 0.0
    while (x < 10.0) {
      println(Math.sqrt(x))
      x += 1.0
    }
    

    The REPL will display ... as a continuation prompt for lines 3-5 of the above, indicating that more input is required to complete the loop. The loop will not execute until the closing brace is entered.

2.2. Kotlinscript

Kotlinscript files have a .kts extension and contain top-level executable code. In effect, there is an implicit main function wrapped around the contents of the file.

  1. Use a text editor to create a file named hello.kts, containing the following:

    println("Hello World")
    
  2. Execute the code in this file like so:

    kotlinc -script hello.kts
    

    Don’t forget the -script option here!

  3. Download grades.kts and open it in a text editor. This is a more substantial example of Kotlinscript. Try running it in the same way as the previous example.

2.3. Creating & Running Programs

  1. Use a text editor to create a file named hello.kt, containing the following code:

    fun main() {
      println("Hello World!")
    }
    
  2. Compile the program like so:

    kotlinc -d hello.jar hello.kt
    
  3. Use ls -l to check the size of hello.jar, then examine its contents like so:

    jar tf hello.jar
    

    You should see that it is quite small - little more than 1 KB in size - and that it contains a file of Java bytecode named HelloKt.class. You can examine the bytecode with this command:

    javap -cp hello.jar -c HelloKt
    

    You can see here that the Kotlin compiler has turned the main function into a Java class containing a main method, so that the code can be executed on the JVM. The name of this class is derived from the name of the original source file.

  4. Run the program like so:

    java -jar hello.jar
    
  5. Now edit hello.kt so that the program issues a personalised greeting to a person named on the command line:

    fun main(args: Array<String>) {
      if (args.size > 0) {
        println("Hello ${args[0]}!")
      }
      else {
        println("Hello World!")
      }
    }
    

    Compile this into JAR file hello.jar as before, then try running the program again. You should get an error message. This problem occurs because the program is now using code from Kotlin’s own libraries, to which the JVM doesn’t have access.

  6. One solution is to run the program differently:

    kotlin -cp hello.jar HelloKt
    

    The kotlin command is aware of Kotlin’s libraries and will ensure that these are included in the classpath before running the program in HelloKt on the JVM. The -cp option modifies the classpath so that the HelloKt class itself can be found.

  7. Another solution is to include the Kotlin runtime libraries in the JAR file. This ensures that the JAR file can be run on the JVM, independently of the Kotlin development tools, but it does make the JAR file substantially larger.

    To include the runtime library files, generate a new version of the JAR file using the following command:

    kotlinc -include-runtime -d hello.jar hello.kt
    

    Check the size of hello.jar again. You should see that is now over 1 MB in size - but at least you can now run it directly on the JVM:

    java -jar hello.jar
    

Note

If you intend using Kotlin from the command line, you can reduce the typing burden by defining shortcuts for the commands used above, e.g.

alias kc=kotlinc
alias kcr='kotlinc -include-runtime'
alias ks='kotlinc -script'

These should go in ~/.bashrc (or ~/.bash_profile if you are on a Mac rather than Linux).