3. Using Kotlin in IntelliJ IDEA

Working with Kotlin from within IntelliJ IDEA is relatively straightforward. Remember that you can get the full professional version of this IDE to use for free on your own PC, but you will need to apply for a student license.

When you run IntelliJ, choose the option to create a new project, then make sure you’ve selected ‘Kotlin/JVM’ as the project type.

../_images/newproj.png

First page of IntelliJ project creation wizard

3.1. The Kotlin REPL

  1. To run the REPL, choose Tools ‣ Kotlin ‣ Kotlin REPL from the menu bar. This will open a new panel at the bottom of the IDE window, within which the REPL is running.

    Try entering a line of Kotlin code. Press Ctrl+Enter to execute it.

    ../_images/repl.png

    Kotlin REPL running within IntelliJ

  2. Now try some code that spans multiple lines:

    var sum = 0
    for (n in 1..10) {
      sum += n
    }
    

    You can run this loop by pressing Ctrl+Enter after having entered the code for the loop body. To see the result, enter sum and press Ctrl+Enter again.

Note

One limitation of the REPL in IntelliJ is that repeated invocations of println() within the same block of code won’t produce output on separate lines!

3.2. Creating & Running Programs

  1. Right-click on the src folder in the Project panel on the left of the IDE and choose New ‣ Kotlin File/Class. Enter hello as the name, leave the Kind field set to ‘File’ and click OK.

  2. In the resulting file hello.kt, implement a simple program:

    fun main(args: Array<String>) {
      println("Hello World!")
    }
    
  3. To run this program, choose Run ‣ Run… from the menu bar, or press Alt+Shift+F10. In the resulting pop-up menu, click on the ‘HelloKt’ option. The program will compile and run, and output will appear in the Run panel at the bottom of the IDE.

    Note that this will create a run configuration of the program. You can run it subsequently by clicking on the ‘green triangle’ in the toolbar at the top right, or by choosing Run ‣ Run ‘HelloKt’, or by pressing Shift+F10.

  4. Another thing you can do in IntelliJ is view the JVM bytecode generated for a particular Kotlin file. Try this now by opening hello.kt and choosing Tools ‣ Kotlin ‣ Show Kotlin Bytecode.