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.
3.1. The Kotlin REPL¶
-
To run the REPL, choose
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.
-
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¶
-
Right-click on the
src
folder in the Project panel on the left of the IDE and choose . Enterhello
as the name, leave the Kind field set to ‘File’ and click OK. -
In the resulting file
hello.kt
, implement a simple program:fun main(args: Array<String>) { println("Hello World!") }
-
To run this program, choose
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
, or by pressing Shift+F10. -
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 .