IntelliJ IDEA 2023.1 Help

Run Kotlin in interactive console

IntelliJ IDEA provides several ways to execute code snippets outside a project. This is useful when you need to quickly evaluate some code fragment, test some scenario, or prototype an improvement.

Kotlin REPL

Kotlin REPL allows you to execute code on the fly without having to create files or configure a runtime environment for it. Also, it accepts simplified syntax so that it is possible to execute code with less ceremony.

Open REPL

  • From the main menu, select Tools | Kotlin | Kotlin REPL (Experimental).

When you enter one or more lines of code and press Control+Enter, the result gets printed in console and assigned to a temporary variable.

val power = 10.0 Math.pow(2.0, power) res0: kotlin.Double = 1024.0

You can then reference these variables and use them in your custom functions.

fun isEven(d: Double) = d.toInt() % 2 == 0 isEven(res0) res1: kotlin.Boolean = true

If required, you can import additional classes and use them in your code snippets

import java.nio.file.* Paths.get("/Users/me.user") res3: java.nio.file.Path! = /Users/me.user Files.walk(res3, 1).forEach {println(it)} /Users/me.user/Users/me.user/IdeaProjects

Scratches and worksheets

Scratches and worksheets allow you to create a temporary file and execute it straight away. This is useful for testing and prototyping purposes. The difference between scratches and worksheets is that:

  • Scratches are independent from projects. They can be accessed from any project, but you have to specify where to look for the classes in case you are using project-specific classes.

  • Worksheets are stored in a project. This lets you use project-specific classes without any configuration, but ties a worksheet to a project.

Create a scratch

  • From the main menu, select File | New | Scratch File or press Control+Alt+Shift+Insert, then select Kotlin.

Create a worksheet

  • In the Project tool window, right-click the directory in which you want to create a worksheet and select New | Kotlin worksheet. Give the worksheet a name and press Enter.

Run a scratch or worksheet

  • In the top-left corner of the editor, click the Run button or press Control+Alt+W.

The following options are available for running Kotlin scratches and worksheets:

  • Use classpath of module (only applicable for scratches): specifies the module with your custom classes if you want to use them in a scratch.

  • Interactive mode: runs the code each time you stop typing.

  • Use REPL: executes the script incrementally. When this option is enabled, you can write and execute code line by line, and only the new code will be executed with each new run.

Last modified: 06 April 2022