cyberangles guide

Exploring the Kotlin REPL: Interactive Programming

In the world of programming, feedback loops are critical. Whether you’re learning a new language, prototyping a feature, or debugging a tricky function, the ability to write code and see results *immediately* can drastically speed up your workflow. This is where REPLs (Read-Eval-Print Loops) shine. A REPL is an interactive programming environment that allows you to input code snippets, execute them, and view the output in real time—no need for full project setups, compilers, or build tools. For Kotlin, a modern JVM language known for its conciseness and interoperability, the REPL is an indispensable tool for developers of all skill levels. In this blog, we’ll dive deep into the Kotlin REPL: what it is, how to access it, its core features, advanced use cases, and tips to make the most of it. By the end, you’ll be equipped to use the Kotlin REPL to learn faster, prototype smarter, and debug more efficiently.

Table of Contents

What is a REPL?

A REPL (Read-Eval-Print Loop) is an interactive programming environment that follows a four-step cycle:

  1. Read: Accepts input (code) from the user.
  2. Eval: Executes (evaluates) the input code.
  3. Print: Displays the result of the execution.
  4. Loop: Repeats the process, waiting for new input.

This cycle eliminates the need for traditional “write-compile-run” workflows, making it ideal for experimentation, learning, and rapid prototyping. REPLs are common in languages like Python, JavaScript, and now Kotlin, where they serve as a bridge between theory and practice.

Getting Started with Kotlin REPL

The Kotlin REPL is available in multiple environments, each with its own strengths. Let’s explore the most popular options:

1. Command-Line REPL

The simplest way to access the Kotlin REPL is via the command line. Here’s how to set it up:

Step 1: Install Kotlin

First, ensure Kotlin is installed on your system. The easiest way is via SDKMAN! (for Linux/macOS) or Chocolatey (for Windows):

  • SDKMAN!:
    sdk install kotlin  
  • Chocolatey:
    choco install kotlin  

Alternatively, download the Kotlin compiler directly from the official Kotlin website.

Step 2: Launch the REPL

Open a terminal and run:

kotlinc  

You’ll see a prompt like >>>, indicating the REPL is ready.

2. IntelliJ IDEA REPL

If you use IntelliJ IDEA (JetBrains’ IDE for Kotlin/Java development), the REPL is built-in and tightly integrated with your project:

  1. Open your Kotlin project in IntelliJ.
  2. Go to Tools > Kotlin > Kotlin REPL (or press Ctrl+Shift+A/Cmd+Shift+A, search for “Kotlin REPL”).
  3. A REPL console will open, pre-configured with your project’s dependencies and classpath.

This is ideal for testing code that relies on project-specific libraries.

3. Online REPLs

For quick experimentation without local setup, use an online Kotlin REPL:

  • Kotlin Playground: JetBrains’ official online REPL with sharing capabilities.
  • JDoodle: Supports Kotlin and other languages, with a simple interface.

These platforms are great for sharing code snippets or testing ideas on the go.

Basic Features of Kotlin REPL

Let’s start with the fundamentals. The Kotlin REPL excels at evaluating simple code and providing instant feedback.

Evaluating Simple Expressions

The REPL can evaluate arithmetic, string, and logical expressions out of the box. Just type an expression and press Enter:

>>> 2 + 2  // Arithmetic  
4  

>>> "Hello, " + "Kotlin!"  // String concatenation  
Hello, Kotlin!  

>>> 10 > 5 && 3 < 4  // Logical operations  
true  

>>> listOf(1, 2, 3).sum()  // Standard library functions  
6  

Note that the REPL prints the result of the expression automatically—no need for println() (though you can use it for explicit output).

Variables: val and var

Kotlin’s type system (with type inference) works seamlessly in the REPL. Declare variables with val (immutable) or var (mutable):

>>> val age = 25  // Immutable variable (type inferred as Int)  
age: Int = 25  

>>> var score = 100  // Mutable variable  
score: Int = 100  

>>> score += 50  // Update mutable variable  
score: Int = 150  

>>> val name: String = "Alice"  // Explicit type (optional)  
name: String = Alice  

The REPL displays the variable name, type, and value, helping you track state.

Defining and Calling Functions

You can define functions in the REPL and call them immediately. Kotlin’s concise syntax makes this trivial:

Simple Functions

>>> fun add(a: Int, b: Int) = a + b  // Single-expression function  
add: (a: Int, b: Int) -> Int  

>>> add(3, 5)  // Call the function  
8  

Multi-Line Functions

For more complex logic, use curly braces:

>>> fun greet(name: String): String {  
...     return "Hello, $name!"  // Explicit return  
... }  
greet: (name: String) -> String  

>>> greet("Bob")  
Hello, Bob!  

The REPL uses ... to indicate a continuation prompt for multi-line input.

Advanced Features of Kotlin REPL

Beyond basics, the Kotlin REPL offers powerful tools for productivity and deeper exploration.

Multi-Line Input

To write code spanning multiple lines (e.g., classes, loops), use Shift+Enter (in IntelliJ) or just press Enter (command-line REPL) to continue input. The REPL will execute only when you finish the block:

>>> class Person(val name: String, var age: Int) {  
...     fun birthday() { age++ }  
... }  
Person  

>>> val alice = Person("Alice", 30)  
alice: Person = Person@5a39699c  

>>> alice.birthday()  
>>> alice.age  
31  

Importing Libraries

The REPL lets you import standard library classes or even third-party dependencies (if configured):

>>> import java.util.Date  // Import from Java standard library  

>>> Date()  // Create a Date object  
Thu Oct 12 14:30:00 UTC 2023  

>>> import kotlin.math.PI  // Kotlin standard library  
>>> PI  
3.141592653589793  

In IntelliJ’s REPL, you can import project-specific dependencies (e.g., com.google.gson.Gson) seamlessly.

Accessing Previous Results

The REPL stores the result of the last 10 evaluations in special variables _1, _2, …, _10. Use them to reference prior outputs:

>>> 2 * 3  // _1 = 6  
6  

>>> _1 + 4  // 6 + 4 = 10  
10  

>>> "Result: $_2"  // _2 = 10  
Result: 10  

History Navigation and Tab Completion

  • History Navigation: Use the Up/Down arrow keys to cycle through previous commands.
  • Tab Completion: Press Tab to auto-complete variable names, functions, or types:
    >>> val message = "Hello"  
    >>> mes  // Press Tab to auto-complete to "message"  

Use Cases for Kotlin REPL

The Kotlin REPL isn’t just a toy—it’s a practical tool for real-world development. Here are its most valuable applications:

Learning Kotlin Basics

For beginners, the REPL is a safe space to experiment with syntax. Instead of writing a full “Hello World” program, you can test concepts like null safety, lambdas, or extension functions in seconds:

>>> val nullable: String? = null  
>>> nullable?.length  // Safe call operator (no NPE!)  
null  

>>> fun String.isPalindrome() = this == reversed()  // Extension function  
>>> "radar".isPalindrome()  
true  

Prototyping Code Snippets

Need to test a regex, date formatter, or algorithm before adding it to your project? The REPL lets you iterate quickly:

>>> import java.time.LocalDate  
>>> import java.time.format.DateTimeFormatter  

>>> val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")  
>>> LocalDate.parse("2023-10-12", formatter)  
2023-10-12  

Once validated, copy the code into your project with confidence.

Debugging and Testing Functions

Isolate bugs by testing problematic functions in the REPL. For example, if a calculateTotal function is returning unexpected results, replicate the input in the REPL:

>>> fun calculateTotal(prices: List<Double>, tax: Double): Double {  
...     return prices.sum() * (1 + tax)  
... }  

>>> calculateTotal(listOf(10.0, 20.0), 0.08)  // Test with sample input  
32.4  // Correct!  

Teaching and Demonstrations

In classrooms or workshops, the REPL is perfect for live coding. Instructors can show how Kotlin’s features work in real time, and students can follow along:

// Demonstrate coroutines (with kotlinx.coroutines imported)  
>>> import kotlinx.coroutines.delay  
>>> import kotlinx.coroutines.runBlocking  

>>> runBlocking {  
...     delay(1000)  // Pause for 1 second  
...     println("Coroutine finished!")  
... }  
Coroutine finished!  // After 1 second  

Tips and Best Practices

To make the most of the Kotlin REPL:

  1. Clear the State: Use :clear (command-line) or Clear All (IntelliJ) to reset variables/functions if your session gets cluttered.
  2. Comment Your Code: Add // comments to remind yourself what you’re testing.
  3. Leverage Online REPLs for Sharing: Use Kotlin Playground to share REPL sessions with teammates or stack overflow.
  4. Avoid Overly Complex Code: The REPL isn’t designed for large programs. Use Kotlin scripts (.kts) for longer logic.
  5. Explore the Standard Library: Use the REPL to discover functions like listOf(1,2,3).filter { it > 1 } or "text".uppercase().

Conclusion

The Kotlin REPL is a versatile tool that bridges the gap between writing code and seeing results. Whether you’re learning Kotlin, prototyping a feature, debugging, or teaching, its interactive nature accelerates productivity and deepens understanding.

By mastering the REPL, you’ll unlock a faster, more iterative approach to development—one where experimentation is encouraged, and feedback is instant. So fire up kotlinc, open IntelliJ, or visit Kotlin Playground, and start exploring!

References