Kotlin 2.1 Up Close – From Non-Local Exits to Multi-Dollar Strings
November 2024 brought the release of Kotlin 2.1. Let's take a look at a few of the language changes that came with the new version.
For Kotlin, last year was an important one, with the major 2.0.0 version released in May. It brought plenty of exciting features, above all the stable K2 compiler, yet it barely touched the design of the language itself. That was no longer the case once version 2.1.0 came out last November. Even though they are still in preview, this release brought a number of language changes that deserve a closer look. This article examines what’s new in Kotlin 2.1, with a focus on the newly added language features.
Prerequisites
A few of the language features added in Kotlin 2.1(covered further on in this article) are still in preview, so you shouldn’t rely on them in production code, as future releases may change or drop them. To use these features in your project, you have to turn them on through compiler options. With Gradle, for instance, put the following in your build file:
kotlin {
compilerOptions {
freeCompilerArgs.add("-X<feature-name>")
}
jvmToolchain(21)
}
The section on each feature further down gives the feature name to place after “-X” (only when the feature needs it).
On top of that, using these language features in IntelliJ IDEA requires version 2024.3.0 or newer with K2 mode turned on. To turn on K2 mode, go to Settings → Languages & Frameworks → Kotlin and tick the “Enable K2 mode” checkbox (the IDE then has to be restarted).
With the basics covered, let’s look at the new features that the latest Kotlin release brings.
Changes to the when expression in Kotlin 2.1
Kotlin’s when expression is a flexible way of controlling program flow and handles multiple conditions concisely. Powerful as it is, it lacks the complete pattern matching capabilities familiar from languages such as Scala. Kotlin 2.1.0 brought improvements that lift some of these limitations. This section looks at what changed in the when expression.
Exhaustiveness checks for when expressions with sealed classes
The newest Kotlin version changes how when expressions with subjects are treated for type parameters whose upper bounds are sealed. Let’s look at exactly what’s different. To illustrate, suppose we have a sealed class describing the possible results of an HTTP request:
sealed class HttpRequestResult {
data class Success(val code: Int, val body: String) : HttpRequestResult()
data class Error(val code: Int, val errorMessage: String) : HttpRequestResult()
object Timeout : HttpRequestResult()
class ConnectionError() : HttpRequestResult()
}
Once we get the request result, we’d like to process it in some way. To keep it simple, let’s say we want to produce a String representation depending on the result type. One way to do that is a function whose type parameter is bounded by our sealed class – HttpRequestResult. Before Kotlin 2.1, a function like that could have looked as follows:
fun <T: HttpRequestResult> processHttpRequestResult(
response: T,
successMapper: (T) -> String,
): String =
when (response ) {
is HttpRequestResult.Success -> successMapper(response)
is HttpRequestResult.Error -> "Error returned by server ${response.code}: ${response.errorMessage}"
is HttpRequestResult.Timeout -> "Connection Timeout"
is HttpRequestResult.ConnectionError -> "Connection error"
else -> "But, why??" // compilation error if else branch is missing
}
Notice that the else branch is mandatory even though the branches above already cover every case of the sealed class. This is an odd quirk of Kotlin before 2.1.0: it demands an else branch in a when expression for type parameters with sealed upper bounds. Without the else branch, compilation fails with this error:
“‘when’ expression must be exhaustive. Add an ‘else’ branch.”
Kotlin 2.1.0 fixes this, so the else branch is no longer necessary:
fun <T: HttpRequestResult> processHttpRequestResult(
response: T,
successMapper: (T) -> String,
): String =
when (response ) {
is HttpRequestResult.Success -> successMapper(response)
is HttpRequestResult.Error -> "Error returned by server ${response.code}: ${response.errorMessage}"
is HttpRequestResult.Timeout -> "Connection Timeout"
is HttpRequestResult.ConnectionError -> "Connection error"
}
That spares us a few needless characters – small things matter! This language feature is stable, so there’s no need to turn on preview mode.
Guard conditions in when with a subject (preview feature “when-guards”)
Next, suppose we want error handling that depends on the error code, producing different string representations for 4XX errors and 5XX errors. Prior to Kotlin 2.1.0, you would probably have done this with nested when or if/else statements:
fun processHttpRequestResult(response: HttpRequestResult): String =
when (response) {
is HttpRequestResult.Success -> "Success with code ${response.code} and body: ${response.body}"
is HttpRequestResult.Error -> {
when (response.code) {
in 400..499 -> "Client's error ${response.code}: ${response.errorMessage}"
500 -> "Server's error ${response.code}: ${response.errorMessage}"
else -> "Other error returned by server ${response.code}: ${response.errorMessage}"
}
}
is HttpRequestResult.Timeout -> "Connection Timeout"
is HttpRequestResult.ConnectionError -> "Connection error"
}
The current Kotlin release brings “guard conditions” to when expressions or statements that have a subject. They let you attach an extra condition to when branches, which makes the control flow more explicit and flattens the code compared with the nested version above:
fun processHttpRequestResultWithGuard(response: HttpRequestResult): String =
when (response) {
is HttpRequestResult.Success -> "Success with code ${response.code} and body: ${response.body}"
is HttpRequestResult.Error if response.code in (400..499) -> "Client's error ${response.code}: ${response.errorMessage}"
is HttpRequestResult.Error if response.code in (500..599) -> "Server's error ${response.code}: ${response.errorMessage}"
is HttpRequestResult.Error -> "Other error returned by server ${response.code}: ${response.errorMessage}"
is HttpRequestResult.Timeout -> "Connection Timeout"
is HttpRequestResult.ConnectionError -> "Connection error"
}
Some properties of this feature:
- A branch’s code runs only when both the primary condition and the guard condition hold.
- A single branch can have several conditions.
- Every logical operator available in an ordinary if/else expression can be used (&&, ||, ! and in).
- Branches with guard conditions can be combined with ordinary branches.
Is this a major change? Not really, but it moves Kotlin closer to the pattern matching found in other languages. Keep in mind that the feature is still in preview and has to be turned on explicitly (see the prerequisites section).
Multi-dollar string interpolation (preview feature “multi-dollar-interpolation”)
Kotlin makes it convenient to write multi-line strings with interpolation. Trouble arises, however, when the string must contain a literal $ sign, which Kotlin uses for interpolation. You run into this often with JSON Schema, where the $ prefix marks keywords that have special meaning. Until now, such cases called for a workaround like ${‘$’}, which can hurt code readability:
val jsonSchema_beforeKotlin2_1_0 = """
{
"${'$'}id" : "https://example/schema/json"
"items" : {
"${'$'}ref" : "#/${'$'}defs/exampleReference",
},
"${'$'}defs" : {
"fileRef" : {
"exampleReference" : "string",
}
}
}
""".trimIndent()
Luckily, Kotlin 2.1.0 lets you decide how many dollar signs start an interpolation. You put that number of dollar signs in front of your multi-line string. Every sequence with exactly that many dollar signs becomes an interpolation marker, while shorter sequences are treated as literal characters. Using this approach, our JSON schema looks like this:
val jsonSchema_multiDollarStringInterpolation = $$"""
{
"$id" : "https://example/schema/json"
"items" : {
"$ref" : "#/$defs/exampleReference",
},
"$defs" : {
"fileRef" : {
"exampleReference" : "$$fileRefType",
}
}
}
""".trimIndent()
In this case, the interpolation prefix is two dollar signs, so no workarounds are needed to output special node names such as $id. Interpolation happens only where two dollar signs appear, as with $fileRefType. Keep in mind that the feature is still in preview, and the “multi-dollar-interpolation” feature has to be turned on.
Non-local break and continue (preview feature “non-local-break-continue”)
Prior to Kotlin 2.1.0, non-local return statements let you leave the enclosing function from inside a lambda, instead of only leaving the lambda. This makes control flow simpler, because invoking the lambda can immediately exit the outer function. It does, however, require the lambda to be passed to an inline function. Let’s see this in action.
Suppose we’re building an event handler that checks whether an event should be processed before it actually handles it. To keep things simple, take a few familiar events from e-commerce order processing, plus a list of events we arbitrarily allow:
enum class EventType {
ORDER_CREATED,
ORDER_CANCELLED,
ORDER_COMPLETED,
ORDER_PAID,
ORDER_DELIVERED,
}
val allowedEvents = setOf(
EventType.ORDER_CREATED,
EventType.ORDER_CANCELLED,
EventType.ORDER_COMPLETED,
)
A simplified version of the code that validates and processes events with a non-local return statement could look like this:
fun handleEvents(events: Set<Event>) {
for (event in events) {
validateEvent(event) { invalidEvent ->
println("Invalid event $invalidEvent")
return
}
println("Event $event is valid")
// processing the event...
}
}
private inline fun validateEvent(event: Event, onValidationError: (Event) -> Unit) {
if (event.eventType !in allowedEvents) {
onValidationError(event)
}
}
Here, the handleEvents function only pretends to process events. The arbitrary validation logic lives in the validateEvent function, which accepts an event and a lambda (Event) -> Unit called when the event isn’t allowed. To keep it simple, the lambda just prints a message and returns from the enclosing function.
This implementation is far from ideal, since it stops processing events as soon as it hits the first invalid one, which isn’t the desired behavior. Its only purpose, though, is to show that a non-local return statement lets us leave the handleEvents function from inside a lambda. Keep in mind that this was already possible before Kotlin 2.1.0.
Let’s go a step further and change the event handler’s requirements so that it prints a summary once all events have been processed. Now we can’t just return from the handleEvents function. We have to leave the for loop first and only then print the summary. A break statement lets us do that. Let’s swap return for break:
internal fun handleEvents(events: Set<Event>) {
for (event in events) {
validateEvent(event) { invalidEvent ->
println("Invalid event $invalidEvent")
break
}
println("Event $event is valid")
// processing the event...
}
println("Processing finished. Summary:...")
}
Compiling this code with Kotlin older than 2.1.0 results in an error (which one exactly depends on the Kotlin version). Starting with Kotlin 2.1.0, though, non-local break statements are available in preview and can be used once the feature is turned on (see the Prerequisites section). Thanks to this, the code compiles and behaves as intended: the for loop stops at the first invalid event and the summary gets printed.
Sharp-eyed readers will spot that although the code works, the compiler emits a warning:
The reason is that the break statement is ambiguous here, and the compiler can’t tell whether it should end the outer for loop or some inner loop that could exist inside the validateEvent function. Because validateEvent is an inline function, its code is pasted straight into the calling function during compilation. There are two ways to remove this ambiguity:
- Add a label that makes it clear which loop to stop.
- Add a callsInPlace contract telling the compiler that onValidationError isn’t called inside an inner loop in validateEvent.
We’ll pick the first option and add a label. This code compiles with no warnings:
internal fun handleEvents(events: Set<Event>) {
forEachEventLoop@ for (event in events) {
validateEvent(event) { invalidEvent ->
println("Invalid event $invalidEvent")
break@forEachEventLoop
}
println("Event $event is valid")
// processing the event...
}
println("Processing finished. Summary:...")
}
Even so, the logic is still not quite right. Processing halts at the very first invalid event, while what we want is to skip invalid events and keep processing the remaining ones. You may already guess that a non-local continue statement gives us exactly that:
fun handleEvents(events: Set<Event>) {
forEachEventsLoop@ for (event in events) {
validateEvent(event) { invalidEvent ->
println("Invalid event $invalidEvent")
continue@forEachEventsLoop
}
println("Event $event is valid")
// processing the event...
}
println("Processing finished. Summary:...")
}
It behaves much like the non-local break (and likewise needs preview mode plus a label or contract). The difference is that, rather than ending the loop, it just moves on to the next iteration whenever it meets an invalid event.
This feature removes an inconsistency in Kotlin – before, non-local return statements were allowed, but break and continue were not. As a result, Kotlin’s lambdas become even more powerful. Keep in mind that non-local break and continue are still in preview, though they are expected to become stable in an upcoming Kotlin release (2.2.0).
Summary
Kotlin 2.1 brings a set of fresh improvements that make your code leaner, more readable and more expressive. The release strengthens Kotlin’s standing as a modern, developer-friendly language and adds several important features:
- The enhanced when expression offers better exhaustiveness checks for sealed classes, so conditional logic can now be written more concisely, without superfluous else branches.
- Guard conditions in the when expression let you put extra filtering straight into
whenexpressions, which flattens the code and makes it easier to read. - Multi-dollar string interpolation makes literal dollar signs in multi-line strings easier to handle, which is especially handy for JSON schemas and other data formats that depend on the
$sign. - Non-local break and continue removes an inconsistency in Kotlin and improves control flow inside lambdas and complex loops.
These language features don’t just make your Kotlin code more powerful; they also pave the way for even more advanced features in upcoming releases. Have fun discovering what Kotlin 2.1 brings and see for yourself how these improvements can change the way you develop.
Since this article concentrates on language features, it doesn’t describe every change in the latest release. To see the complete list of changes, I recommend reading this release note.