Run Kotlin in interactive console
IntelliJ IDEA provides several ways to execute code snippets outside of 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
.
When you enter one or more lines of code and press Ctrl+Enter, the result gets printed in console and assigned to a temporary variable.
You can then reference these variables and use them in your custom functions.
If required, you can import additional classes and use them in your code snippets
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 Kotlin.
or press Ctrl+Alt+Shift+Insert, then Select
Create a worksheet
In the Project tool window, select the directory in which you want to create a worksheet, then press Ctrl+Alt+Shift+Insert. Alternatively, right-click the directory and select . Give the worksheet a name and press Enter
Run a scratch or worksheet
In the top-left corner of the editor, click or press Ctrl+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.
Make module before run – compiles the module each time you run the code snippet.
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.