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 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.
In the main menu, go to Tools | Kotlin | Kotlin REPL (Experimental).
When you enter one or more lines of code and press CtrlEnter, 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
note
Besides Kotlin REPL, you can use Kotlin Notebook to write code, run it on the fly, and see immediate outputs. To explore more about this tool, see Kotlin Notebook.
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.
In the main menu, go to File | New | Scratch File or press CtrlAltShiftInsert, then select Kotlin.
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.
In the top-left corner of the editor, click
or press CtrlAlt0W.
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.
Thanks for your feedback!