Last Updated | 24 December 2018 |
Sometimes you may need to quickly write and execute some code outside of a project or an application. This may be useful, for example, when learning Kotlin or evaluating expressions. Let's have a look through two handy ways to quickly run Kotlin code:
Currently, scratches are supported only in Kotlin/JVM projects.
Kotlin plugin for IntelliJ IDEA supports scratches. Scratches let you create code drafts in the same IDE window with your project and run them on the fly. Scratches are not tied to projects; you can access and run all your scratches from any IntelliJ IDEA window on your OS.
To create a Kotlin scratch, click File | New | Scratch file and select the Kotlin type.
In your scratch, you can write any valid Kotlin code, including new functions and classes. Syntax highlighting, auto-completion, and other code editing features of IntelliJ IDEA are supported in scratches.
Write your code in the scratch and click Run. The execution results will appear opposite the lines of your code.
IntelliJ IDEA can run your scratches automatically. To get the execution results once you stop typing for a short time, switch on the Interactive mode.
To use classes or functions from a project in the scratch, import them into the scratch file as usual with the import
statement. Then write your code and run it with the appropriate module selected in Use classpath of module list. To rebuild the module automatically before running the scratch, select Make before Run.
To evaluate each particular expression in a scratch, run it with Use REPL selected. The scratch will be executed the same way as in REPL: the code lines will run subsequently, providing results of each call. You can later refer to the results by the names res*
shown in the corresponding lines.
REPL (Read-Eval-Print-Loop) is a tool for running Kotlin code interactively. REPL lets you evaluate expressions and code chunks without creating projects or even functions if you don't need them.
To run REPL in IntelliJ IDEA, open Tools | Kotlin | Kotlin REPL.
To run REPL in the OS command line, open /bin/kotlinc-jvm from the directory of standalone Kotlin compiler.
The REPL command line interface opens. You can enter any valid Kotlin code and see the result. Results are printed as variables with auto-generated names like res*
. You can later use such variables in the code you run in REPL.
REPL supports multiple line input as well. The result of a multiple line input is the value of its last expression.
© 2010–2019 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/docs/tutorials/quick-run.html