Bird
Raised Fist0
Kotlinprogramming~15 mins

Kotlin REPL and script mode - Deep Dive

Choose your learning style10 modes available
Overview - Kotlin REPL and script mode
What is it?
Kotlin REPL is an interactive tool where you can type Kotlin code and see the results immediately. Script mode lets you write Kotlin code in a file and run it directly without compiling a full project. Both help you quickly test ideas or small programs without setting up a full development environment.
Why it matters
These tools make learning and experimenting with Kotlin fast and easy. Without them, you would need to write full programs, compile, and run them every time you want to try something new. This slows down learning and exploration, especially for beginners or quick tests.
Where it fits
Before this, you should know basic Kotlin syntax and how to write simple programs. After mastering REPL and script mode, you can move on to building full Kotlin applications using IDEs and build tools like Gradle.
Mental Model
Core Idea
Kotlin REPL and script mode let you write and run Kotlin code instantly, making coding feel like a conversation rather than a long process.
Think of it like...
It's like chatting with a friend who instantly answers your questions, instead of writing a letter and waiting days for a reply.
┌───────────────┐       ┌───────────────┐
│  Kotlin REPL  │──────▶│ Immediate     │
│  (interactive)│       │ feedback      │
└───────────────┘       └───────────────┘

┌───────────────┐       ┌───────────────┐
│ Kotlin Script │──────▶│ Run Kotlin    │
│ (file mode)   │       │ code quickly  │
└───────────────┘       └───────────────┘
Build-Up - 6 Steps
1
FoundationWhat is Kotlin REPL?
🤔
Concept: Introducing the Kotlin REPL as an interactive tool for running Kotlin code line-by-line.
Kotlin REPL stands for Read-Eval-Print Loop. It lets you type Kotlin commands one at a time and immediately see the result. You can start it by running 'kotlinc' and then typing commands.
Result
You get instant feedback on your Kotlin code without writing a full program.
Understanding REPL helps you experiment with Kotlin quickly and learn by doing.
2
FoundationWhat is Kotlin Script Mode?
🤔
Concept: Explaining Kotlin script mode as running Kotlin code saved in a file directly.
Kotlin script mode lets you write Kotlin code in a file with a '.kts' extension. You run it using 'kotlinc -script filename.kts' or 'kotlin filename.kts'. This runs the code without needing to compile a full project.
Result
You can run small Kotlin programs or automation scripts easily.
Script mode bridges quick testing and real programs by letting you write runnable Kotlin files.
3
IntermediateUsing Kotlin REPL for quick tests
🤔Before reading on: do you think REPL can remember variables between commands? Commit to your answer.
Concept: Showing how REPL keeps state so you can define variables and use them later.
In Kotlin REPL, if you type 'val x = 5', you can later type 'x + 3' and get 8. The REPL remembers your variables and functions until you exit.
Result
You can build up code step-by-step interactively.
Knowing REPL keeps state helps you plan experiments and debug code interactively.
4
IntermediateWriting and running Kotlin scripts
🤔Before reading on: do you think Kotlin scripts support all Kotlin language features? Commit to your answer.
Concept: Explaining what Kotlin scripts can do and their limitations compared to full Kotlin programs.
Kotlin scripts (.kts files) support most Kotlin features like functions, variables, and imports. However, they are designed for quick tasks and may not support complex project structures or some advanced features without extra setup.
Result
You can write useful scripts for automation, configuration, or quick tasks.
Understanding script mode's scope helps you choose when to use scripts vs full projects.
5
AdvancedIntegrating Kotlin scripts with tools
🤔Before reading on: do you think Kotlin scripts can be used as build scripts or automation tools? Commit to your answer.
Concept: Showing how Kotlin scripts are used in real tools like Gradle and automation.
Kotlin scripts are used as build scripts in Gradle (build.gradle.kts). They let you write build logic in Kotlin instead of Groovy. You can also write automation scripts for tasks like file processing or deployment.
Result
Kotlin scripts become powerful tools beyond simple tests.
Knowing scripts power real tools shows their practical importance and flexibility.
6
ExpertREPL internals and script compilation
🤔Before reading on: do you think REPL compiles each line separately or as a whole? Commit to your answer.
Concept: Explaining how REPL compiles and runs code behind the scenes and how scripts are executed.
Kotlin REPL compiles each entered line into bytecode and keeps it in memory, linking new lines to previous ones to maintain state. Scripts are compiled as a single unit and then executed. This design balances interactivity with performance.
Result
You understand why REPL feels instant and how scripts run efficiently.
Understanding compilation internals explains REPL's speed and script mode's behavior.
Under the Hood
Kotlin REPL reads each line you type, compiles it into JVM bytecode, and executes it immediately, storing variables and functions in memory to keep state. Script mode compiles the entire script file into bytecode before running it, allowing more complex code but less interactivity.
Why designed this way?
REPL was designed for fast feedback during learning and debugging, so compiling line-by-line keeps it responsive. Script mode was created to let Kotlin be used for scripting tasks without full project overhead, balancing ease of use and power.
┌───────────────┐
│ User types    │
│ Kotlin code   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ REPL compiler │
│ compiles line │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ JVM executes  │
│ bytecode      │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ State stored  │
│ in memory     │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does Kotlin REPL lose all variables after each line? Commit yes or no.
Common Belief:Kotlin REPL forgets everything after each line, so you can't build on previous code.
Tap to reveal reality
Reality:REPL keeps all variables, functions, and classes in memory until you exit, allowing you to build code step-by-step.
Why it matters:Believing REPL forgets state stops learners from experimenting interactively and slows learning.
Quick: Can Kotlin scripts use all Kotlin language features? Commit yes or no.
Common Belief:Kotlin scripts are very limited and can't use normal Kotlin features like functions or imports.
Tap to reveal reality
Reality:Kotlin scripts support most Kotlin features including functions, variables, imports, and even calling Java code.
Why it matters:Underestimating scripts limits their use for automation and quick tasks.
Quick: Is Kotlin REPL the same as running a Kotlin script file? Commit yes or no.
Common Belief:REPL and script mode are exactly the same in how they run code.
Tap to reveal reality
Reality:REPL runs code line-by-line interactively, while script mode compiles and runs the whole file at once.
Why it matters:Confusing them leads to wrong expectations about interactivity and performance.
Quick: Can Kotlin scripts replace full Kotlin projects for big apps? Commit yes or no.
Common Belief:You can write large, complex applications entirely as Kotlin scripts.
Tap to reveal reality
Reality:Scripts are best for small tasks; full projects with build tools are needed for large apps.
Why it matters:Trying to build big apps as scripts causes maintenance and performance problems.
Expert Zone
1
REPL uses a classloader trick to keep compiled code in memory, allowing incremental compilation and execution.
2
Scripts can declare dependencies and use annotations to customize execution, enabling advanced automation.
3
REPL sessions can be saved and restored using special tools, which is useful for long experiments.
When NOT to use
Avoid REPL and scripts for large, multi-module applications or when performance and packaging are critical. Use full Kotlin projects with Gradle or Maven instead.
Production Patterns
Kotlin scripts are widely used in Gradle build scripts (build.gradle.kts) and automation tasks like CI/CD pipelines. REPL is mainly a learning and debugging tool.
Connections
Python REPL and scripting
Similar interactive and script modes for quick coding and automation.
Knowing Kotlin REPL and scripts helps understand Python's interactive shell and scripts, showing a common pattern in modern languages.
Command line shells (bash, zsh)
Script mode is like shell scripting, automating tasks with code run directly from files.
Understanding Kotlin scripts as automation tools connects programming with system administration and DevOps.
Live coding in music performance
Both involve writing code live and getting immediate feedback to create or modify output.
Seeing REPL as a live coding tool reveals parallels between programming and creative arts, emphasizing interactivity.
Common Pitfalls
#1Trying to run multi-file Kotlin projects in REPL.
Wrong approach:In REPL, typing code that depends on other files without loading them causes errors.
Correct approach:Use a full Kotlin project with Gradle or compile all files together outside REPL.
Root cause:REPL only runs code interactively line-by-line and does not handle multi-file dependencies.
#2Writing complex application logic in Kotlin scripts.
Wrong approach:Putting large classes and many modules in a single .kts script file.
Correct approach:Organize code into a Kotlin project with proper modules and build tools.
Root cause:Scripts are designed for small tasks; large codebases need structured projects.
#3Expecting REPL to save your session automatically.
Wrong approach:Closing REPL and expecting variables and code to be there next time.
Correct approach:Save code in files or use tools to save REPL sessions explicitly.
Root cause:REPL stores state only in memory during the session, not on disk.
Key Takeaways
Kotlin REPL lets you write and run Kotlin code interactively, giving instant feedback and keeping state between commands.
Kotlin script mode runs Kotlin code saved in files quickly without full project setup, ideal for automation and small tasks.
REPL compiles and executes code line-by-line, while scripts compile the whole file before running.
Scripts support most Kotlin features but are not suited for large, complex applications.
Understanding these tools accelerates learning, experimentation, and practical use of Kotlin in real-world tasks.

Practice

(1/5)
1. What is the main purpose of Kotlin REPL?
easy
A. To run Kotlin code interactively line by line
B. To compile Kotlin code into Java bytecode
C. To create Android applications
D. To manage Kotlin project dependencies

Solution

  1. Step 1: Understand REPL meaning

    Kotlin REPL stands for Read-Eval-Print Loop, which runs code interactively.
  2. Step 2: Identify REPL use

    It lets you type and run Kotlin code line by line without compiling a full program.
  3. Final Answer:

    To run Kotlin code interactively line by line -> Option A
  4. Quick Check:

    Kotlin REPL = Interactive code running [OK]
Hint: REPL runs code line by line interactively [OK]
Common Mistakes:
  • Confusing REPL with full project compilation
  • Thinking REPL is for app deployment
  • Assuming REPL manages dependencies
2. Which file extension is used for Kotlin script files?
easy
A. .kts
B. .skr
C. .kotlin
D. .kt

Solution

  1. Step 1: Recall Kotlin file types

    Kotlin source files usually use .kt extension for normal programs.
  2. Step 2: Identify script file extension

    Kotlin scripts use .kts extension to run code without full compilation.
  3. Final Answer:

    .kts -> Option A
  4. Quick Check:

    Kotlin script files = .kts [OK]
Hint: Scripts use .kts extension, not .kt [OK]
Common Mistakes:
  • Choosing .kt which is for normal Kotlin files
  • Assuming .kotlin or .skr are valid extensions
  • Mixing script files with compiled files
3. What is the output of this Kotlin REPL session?
val x = 5
val y = 10
x + y
medium
A. 510
B. Error: undefined variables
C. x + y
D. 15

Solution

  1. Step 1: Evaluate variable assignments

    x is assigned 5, y is assigned 10 in REPL environment.
  2. Step 2: Calculate expression result

    x + y equals 5 + 10 which is 15.
  3. Final Answer:

    15 -> Option D
  4. Quick Check:

    5 + 10 = 15 [OK]
Hint: Add values assigned to variables for output [OK]
Common Mistakes:
  • Concatenating numbers as strings (510)
  • Printing expression text instead of result
  • Assuming variables are undefined in REPL
4. Identify the error in this Kotlin script file example.kts:
val name = "Alice"
println(Name)
medium
A. Script files cannot use println
B. Variable 'Name' is not defined (case sensitive)
C. Missing semicolon after println statement
D. String literals must use single quotes

Solution

  1. Step 1: Check variable usage

    Variable declared as 'name' but used as 'Name' which differs in case.
  2. Step 2: Understand Kotlin case sensitivity

    Kotlin variables are case sensitive, so 'Name' is undefined causing error.
  3. Final Answer:

    Variable 'Name' is not defined (case sensitive) -> Option B
  4. Quick Check:

    Variable names are case sensitive [OK]
Hint: Check variable name case carefully [OK]
Common Mistakes:
  • Thinking semicolons are mandatory
  • Believing println is disallowed in scripts
  • Using single quotes for strings in Kotlin
5. You want to quickly test a Kotlin function without creating a full project. Which approach is best?
hard
A. Write the function in Java and call it from Kotlin
B. Create a full Kotlin project and add the function
C. Use Kotlin REPL to define and test the function interactively
D. Write the function in a .kts script file and run it

Solution

  1. Step 1: Compare quick testing methods

    Creating a full project is slow; writing Java adds complexity.
  2. Step 2: Choose between script and REPL

    REPL lets you define and test functions interactively without saving files.
  3. Step 3: Understand REPL advantage

    REPL is fastest for quick tests; scripts require saving and running files.
  4. Final Answer:

    Use Kotlin REPL to define and test the function interactively -> Option C
  5. Quick Check:

    REPL = fastest interactive testing [OK]
Hint: Use REPL for fastest interactive function testing [OK]
Common Mistakes:
  • Assuming scripts are faster than REPL
  • Thinking full projects are needed for tests
  • Confusing Java code with Kotlin quick tests
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard