编辑本页

Running Code Snippets

最近更新 2018-12-24
This tutorial shows the ways to run Kotlin code snippets in a lightweight manner without creating or modifying the whole project.

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:

  • Scratches let you write and run code in a temporary file outside your project in IDE.
  • REPL (Read-Eval-Print-Loop) runs code interactively in a console.

Using Scratches

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.

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.

Scratch select module

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 will run subsequently, providing results of each call. You can later refer to the results by the names res* that are shown in the corresponding lines.

Scratch REPL

Running in REPL

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.