Interactive shell
suggest changeMany languages come with an interactive shell (a REPL, read-eval-print loop) for trying out a line of code without creating a project. Kotlin had one in kotlinc for years, but it's deprecated and no longer works in current compilers. This article covers what to use instead:
| Tool | Best for |
|---|---|
kotlin -e '...' |
evaluating one expression from the terminal |
.main.kts scripts |
short programs with Maven dependencies, no build file |
| Kotlin Notebook, scratch files, Playground | interactive exploration with state |
jshell + Kotlin stdlib |
quick checks of JDK APIs |
| JSR-223 script engine | building a Kotlin REPL into your own app |
| JLine | building a command shell for your own app |
All examples were run with Kotlin 2.4.21 on JDK 25.
The kotlinc REPL is gone
Running kotlinc without arguments used to start a REPL. In Kotlin 2.x it refuses:
$ kotlinc
error: Kotlin REPL is deprecated and should be enabled explicitly for now; please use the '-Xrepl' option
Enabling it explicitly doesn't help either, because the 2.4 compiler no longer ships the scripting plugin the old REPL needs:
$ kotlinc -Xrepl
error: unable to run REPL, no scripting plugin loaded
$ kotlin -repl
error: unable to run REPL, no scripting plugin loaded
JetBrains retired the old REPL in favor of Kotlin Notebook and scripts. The rest of this article shows the alternatives.
Evaluating an expression with -e
kotlin -e (or kotlinc -e) compiles the string as a script, runs it, and prints the value of the last expression:
$ kotlin -e '2 + 2'
4
$ kotlin -e '(1..10).filter { it % 3 == 0 }.sum()'
18
$ kotlin -e '"%.3f".format(Math.PI)'
3.142
$ kotlin -e 'Runtime.version()'
25.0.4.1+1-LTS
If the last expression is Unit or null, nothing is printed. Output from println shows up as usual:
$ kotlin -e 'println(listOf(3, 1, 2).sorted())'
[1, 2, 3]
The string can span several lines and use imports, which is handy in a shell with multi-line quotes:
$ kotlin -e 'import java.time.LocalDate
val d = LocalDate.of(2026, 10, 17)
d.dayOfWeek'
SATURDAY
Extra command-line arguments go into args:
$ kotlin -e 'args.map { it.toInt() }.sum()' 4 5 6
15
Errors are reported like normal compiler errors, with a non-zero exit code: 1 for compilation errors and 3 for an exception thrown while running:
$ kotlin -e 'val x: Int = "s"'
script.kts:1:12: error: initializer type mismatch: expected 'Int', actual 'String'.
val x: Int = "s"
^
$ echo $?
1
$ kotlin -e 'error("boom")'
java.lang.IllegalStateException: boom
at Script.<init>(script.kts:1)
$ echo $?
3
Every call starts a JVM and the compiler, so each one takes a few seconds. That's fine for a one-off check, but too slow for a back-and-forth session.
Scripts with .main.kts
A file ending in .main.kts is a script: top-level statements run from top to bottom, and there's no main function. It's the easiest way to try a library without setting up Gradle, because @file:DependsOn downloads a dependency from Maven Central:
// explore.main.kts
@file:DependsOn("com.google.code.gson:gson:2.13.1")
import com.google.gson.GsonBuilder
data class Point(val x: Int, val y: Int)
val gson = GsonBuilder().setPrettyPrinting().create()
val json = gson.toJson(listOf(Point(1, 2), Point(3, 4)))
println(json)
val back = gson.fromJson(json, Array<Point>::class.java)
println(back.toList())
println("args: ${args.toList()}")
$ kotlin explore.main.kts one two
[
{
"x": 1,
"y": 2
},
{
"x": 3,
"y": 4
}
]
[Point(x=1, y=2), Point(x=3, y=4)]
args: [one, two]
The first run took about 8 seconds because it downloaded Gson and compiled the script. Later runs reuse the cached result and start faster (about 2 seconds here).
Other useful annotations:
@file:Repository("https://...")adds a Maven repository besides Maven Central.@file:Import("other.main.kts")pulls in declarations from another script.@file:CompilerOptions("-opt-in=kotlin.RequiresOptIn")passes options to the compiler.
Scripts can read standard input, so they also work as small Unix-style filters. This one imports a helper from another script and uses __FILE__, which .main.kts scripts get for free:
// helpers.main.kts
fun mean(xs: List<Double>) = xs.sum() / xs.size
// stats.main.kts
@file:Import("helpers.main.kts")
val numbers = generateSequence(::readLine)
.flatMap { it.split(' ', ',').asSequence() }
.filter { it.isNotBlank() }
.map { it.toDouble() }
.toList()
println("script: ${__FILE__.name}")
println("count=${numbers.size} min=${numbers.min()} max=${numbers.max()} mean=${mean(numbers)}")
$ printf '3 1 4\n1,5,9\n2 6\n' | kotlin stats.main.kts
script: stats.main.kts
count=8 min=1.0 max=9.0 mean=3.875
On Linux and macOS a script can start with #!/usr/bin/env kotlin and be run directly after chmod +x (see comments and documentation).
Interactive tools in the IDE and browser
For a real session where variables stay alive between steps, use one of these:
- Kotlin Notebook (IntelliJ IDEA): a Jupyter-style notebook in a
.ipynbfile. Each cell keeps the state of the cells run before it, results are shown under the cell (including tables and charts), and%useadds popular libraries in one line, for example%use dataframeor%use ktor-client. Outside IntelliJ, the same engine is available as a Jupyter kernel (pip install kotlin-jupyter-kernel). - Scratch files (IntelliJ IDEA: File > New > Scratch File > Kotlin): a throwaway
.ktsfile that isn't part of the project. With Interactive mode turned on, it re-runs as you type and shows each line's result in the right margin. It can use the classpath of a module from your project, which makes it a good place to call your own code. - Kotlin Playground (play.kotlinlang.org): runs Kotlin in the browser with nothing installed. You can pick the Kotlin version and target (JVM, JS, Wasm) and share a snippet as a link.
- The debugger: when paused at a breakpoint, Evaluate Expression (
Alt+F8) runs any Kotlin code against the live program state. See debugging.
Ki, the separate Kotlin interactive shell from JetBrains, is no longer actively developed and doesn't track current Kotlin versions.
jshell with the Kotlin standard library
The JDK's jshell is a working REPL. It only understands Java, but if you put the Kotlin standard library on its class path you can call Kotlin code from it, too. Kotlin top-level functions are compiled into classes named after the file, such as CollectionsKt or StringsKt:
$ jshell --class-path /path/to/kotlinc/lib/kotlin-stdlib.jar
jshell> import kotlin.collections.CollectionsKt
jshell> import kotlin.text.StringsKt
jshell> var xs = CollectionsKt.listOf(3, 1, 2)
xs ==> [3, 1, 2]
jshell> CollectionsKt.sorted(xs)
$4 ==> [1, 2, 3]
jshell> StringsKt.reversed("hello")
$5 ==> olleh
jshell> kotlin.KotlinVersion.CURRENT
$6 ==> 2.4.21
This is clumsy for Kotlin code, but useful for exploring a JDK API or a compiled JAR of your own (add it to --class-path).
Building a Kotlin REPL into your app
The Kotlin scripting engine implements the standard Java scripting API (JSR-223, javax.script). With it you can embed a Kotlin REPL in your own program, for example as an admin console for a running server. Add the engine and a current kotlin-reflect (the version it pulls in transitively is very old):
// build.gradle.kts
dependencies {
implementation("org.jetbrains.kotlin:kotlin-scripting-jsr223:2.4.21")
runtimeOnly("org.jetbrains.kotlin:kotlin-reflect:2.4.21")
}
The engine keeps state between eval() calls, so a variable or function defined in one snippet can be used in the next. engine.put() exposes objects from the host program to snippets:
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import javax.script.ScriptException
class AppState {
val users = mutableListOf("ann", "bob")
fun addUser(name: String) { users += name }
}
// true when stdin is a file or a pipe instead of a person typing
val echoInput = System.console()?.isTerminal != true
fun readSnippet(): String? {
val sb = StringBuilder()
var depth = 0
do {
print(if (sb.isEmpty()) "kt> " else "... ")
System.out.flush()
val line = readlnOrNull() ?: return null // end of input
if (echoInput) println(line)
sb.appendLine(line)
depth += line.count { it == '{' || it == '(' } - line.count { it == '}' || it == ')' }
} while (depth > 0)
return sb.toString().trim()
}
fun evalAndPrint(engine: ScriptEngine, code: String) {
try {
val result = engine.eval(code)
if (result != null && result != Unit) println("res: $result")
} catch (e: ScriptException) {
val compileErrors = e.message.orEmpty().lines().filter { it.startsWith("ERROR") }
if (compileErrors.isNotEmpty()) compileErrors.forEach(::println)
else println("exception: ${e.cause ?: e}")
}
}
fun main() {
val engine = ScriptEngineManager().getEngineByExtension("kts")
?: error("Kotlin script engine not found on the classpath")
engine.put("app", AppState()) // visible to snippets as `app`
println("Kotlin ${KotlinVersion.CURRENT} shell. :quit to exit")
while (true) {
val code = readSnippet() ?: break
when {
code.isEmpty() -> continue
code == ":quit" -> break
else -> evalAndPrint(engine, code)
}
}
println("bye")
}
How it works:
getEngineByExtension("kts")finds the Kotlin engine through the service loader. It returnsnullif the scripting JARs are missing.readSnippet()keeps reading lines while there are unclosed{or(, so a multi-line function can be typed in. The counting is naive (a brace inside a string confuses it), but it's good enough for a console.readlnOrNull()returnsnullat end of input (Ctrl+Don Unix,Ctrl+Zthen Enter on Windows), which ends the loop. See reading input from command line.- Compilation errors arrive as a
ScriptExceptionwhose message lists each error on a line starting withERROR. Exceptions thrown by the snippet itself are wrapped in aScriptExceptiontoo, with the original ascause. - When input comes from a pipe, the shell echoes each line so the transcript is readable.
Running it with a session fed from a file:
$ cat session.txt
val names = listOf("Ann", "Bob", "Cy")
names.map { it.length }
fun greet(name: String): String {
return "Hello, $name!"
}
names.map(::greet)
var count = 0
count += 5
count
app.users
app.addUser("cy")
app.users.size
val n: Int = "oops"
missing + 1
1 / 0
println("printed, no result")
:quit
$ java --sun-misc-unsafe-memory-access=allow -cp <classpath> ReplKt < session.txt
Kotlin 2.4.21 shell. :quit to exit
kt> val names = listOf("Ann", "Bob", "Cy")
kt> names.map { it.length }
res: [3, 3, 2]
kt> fun greet(name: String): String {
... return "Hello, $name!"
... }
kt> names.map(::greet)
res: [Hello, Ann!, Hello, Bob!, Hello, Cy!]
kt> var count = 0
kt> count += 5
kt> count
res: 5
kt> app.users
res: [ann, bob]
kt> app.addUser("cy")
kt> app.users.size
res: 3
kt> val n: Int = "oops"
ERROR Initializer type mismatch: expected 'Int', actual 'String'. (snippet_10.repl.kts:1:12)
kt> missing + 1
ERROR Unresolved reference 'missing'. (snippet_11.repl.kts:1:1)
kt> 1 / 0
exception: java.lang.ArithmeticException: / by zero
kt> println("printed, no result")
printed, no result
kt> :quit
bye
Things to know:
- The first snippet takes several seconds while the embedded compiler warms up. Later snippets are much faster.
- On JDK 24 and later, the compiler triggers a
sun.misc.Unsafedeprecation warning at startup.--sun-misc-unsafe-memory-access=allowsilences it. - The engine adds about 65 MB of JARs (most of it is the compiler) to your app.
- A snippet can do anything your program can: read files, open sockets, call
System.exit(). Only expose a REPL like this to trusted users, for example on a port bound to localhost.
Building a command shell with JLine
Sometimes the shell you need isn't a Kotlin REPL but a set of commands for your app, like redis-cli or psql. readlnOrNull() works, but it has no line editing, no history and no tab completion. JLine adds all three, and on Windows it handles the console API too:
// build.gradle.kts
dependencies {
implementation("org.jline:jline:4.4.8")
}
This is a small key-value store with a command prompt:
import org.jline.reader.EndOfFileException
import org.jline.reader.LineReader
import org.jline.reader.LineReaderBuilder
import org.jline.reader.UserInterruptException
import org.jline.reader.impl.completer.StringsCompleter
import org.jline.terminal.TerminalBuilder
import kotlin.io.path.Path
val store = sortedMapOf<String, String>()
val commands: Map<String, (List<String>) -> String> = mapOf(
"set" to { a -> require(a.size == 2) { "usage: set <key> <value>" }; store[a[0]] = a[1]; "ok" },
"get" to { a -> store[a.getOrNull(0)] ?: "(nil)" },
"del" to { a -> if (store.remove(a.getOrNull(0)) != null) "deleted" else "(nil)" },
"list" to { _ -> store.entries.joinToString("\n") { "${it.key} = ${it.value}" }.ifEmpty { "(empty)" } },
"help" to { _ -> "commands: set get del list help quit" },
)
fun main() {
val terminal = TerminalBuilder.builder().build()
val reader = LineReaderBuilder.builder()
.terminal(terminal)
.completer(StringsCompleter(commands.keys + "quit"))
.variable(LineReader.HISTORY_FILE, Path(System.getProperty("user.home"), ".kvshell_history"))
.build()
while (true) {
val line = try {
reader.readLine("kv> ")
} catch (e: UserInterruptException) { // Ctrl+C: drop the current line
continue
} catch (e: EndOfFileException) { // Ctrl+D or end of piped input
break
}
val words = reader.parsedLine.words().filter { it.isNotEmpty() }
if (words.isEmpty()) continue
val name = words[0]
if (name == "quit") break
val cmd = commands[name]
val output = try {
cmd?.invoke(words.drop(1)) ?: "unknown command '$name', try help"
} catch (e: IllegalArgumentException) {
e.message
}
terminal.writer().println(output)
}
terminal.close()
}
What JLine gives you here:
- Line editing: arrow keys,
Home/End,Ctrl+Wto delete a word, and the other usual Emacs-style keys. - History: up and down arrows go through earlier lines, and
Ctrl+Rsearches them.HISTORY_FILEsaves history across runs. - Completion: pressing
Tabcompletes command names from theStringsCompleter. For context-aware completion (say, completing keys afterget), useArgumentCompleteror write your ownCompleter. - Parsing:
parsedLine.words()splits the line the way a shell does, so"hello world"in quotes is one argument. - Signals:
Ctrl+CthrowsUserInterruptExceptioninstead of killing the process, andCtrl+DthrowsEndOfFileException.
Running it with input piped from a file (in this mode JLine falls back to a plain terminal and doesn't echo what was typed, so only the prompts and replies show):
$ cat kv.txt
help
set lang Kotlin
set greeting "hello world"
get greeting
list
set oops
del lang
get lang
frob
quit
$ java --enable-native-access=ALL-UNNAMED -cp <classpath> KvShellKt < kv.txt
kv> commands: set get del list help quit
kv> ok
kv> ok
kv> hello world
kv> greeting = hello world
lang = Kotlin
kv> usage: set <key> <value>
kv> deleted
kv> (nil)
kv> unknown command 'frob', try help
kv>
--enable-native-access=ALL-UNNAMED lets JLine use the JDK's foreign function API to talk to the terminal without a JDK warning. To ship a shell like this as a single command, see building and distributing programs, and for parsing the flags it's started with, see command-line arguments.
Which one to use
- One quick calculation or API check:
kotlin -e '...'. - A short program, especially one that needs a library: a
.main.ktsscript. - Exploring step by step, with results kept around: Kotlin Notebook or a scratch file.
- Running code against a live program: the debugger's Evaluate Expression, or an embedded JSR-223 REPL if the program runs outside an IDE.
- A command interface for users of your tool: JLine.