Issue with Kotlin Scratch Files in IntelliJ Idea

I've recently started a new job on a project that uses Kotlin heavily. For those that don't know, Kotlin is an open-source, statically typed programming language created by JetBrains. It was designed to interoperate fully with Java, but also compiles to JavaScript or native code. As a primarily Java developer for most of my career, I've been intrigued by JVM-based languages like Groovy, Clojure, and Kotlin, and I'm super excited to be able to do more than just dabble in Kotlin.

I've also been a long time JetBrains IntelliJ Idea user and I love their Scratch files feature. It's a quick way to experiment with small pieces of code that gives you instant feedback. I use it all the time when learning a new library, getting familiar with a new class, or trying to understand new concepts. One of its best features is being able to use any class or library on your project's classpath. Also, it's a type of REPL (Read Evaluate Print Loop), so you get instant feedback; which is great for failing and learning.

Recently, I was trying to better understand Kotlin coroutines using a Kotlin Scratch file and ran into some weird issues. Specifically I was creating a few small functions and then tried invoking them, but received an odd error. To provide a simplified example of the problem, my scratch file looked something like this:

fun hello() = println("Hello World")

And the error was:

error: unresolved reference: hello

I was totally confused. Since I'm fairly new to Kotlin, I thought I was doing something stupid related to Kotlin. All my searches for "Idea Kotlin Scratch file create and call function" didn't offer any help. So then I thought maybe the order was important, so I moved the invocation to below the function:

fun hello() = println("Hello World")

That appeared to fix my issue so I thought that was the end of it. Until I started researching to write this article, and realized calling the function first worked if I unchecked Use REPL in the Scratch file's configuration as shown here:

Screen Shot 2022-04-07 at 11.12.01 AM.png

The hover tip for Use REPL states:

Runs in the Kotlin REPL. Executes only the new expressions added to the end of the scratch

That seems odd to me because I believe a typical REPL in other languages executes the whole piece of code and not just "new expressions added at the end". Either way, if you see this error, you might check your Scratch file's configuration and try unchecking Use REPL.