BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Kotlin Reaches 2.1.0, Bringing New Language Features, Compiler Updates, and More

Kotlin Reaches 2.1.0, Bringing New Language Features, Compiler Updates, and More

Kotlin 2.1.0 introduces new syntax, including guard conditions, non-local break and continue, and multi-dollar string interpolation. Additionally, it extends its multiplatform capabilities and improves the K2 compiler.

Guard conditions in when expressions are meant to make conditional logic more concise and readable. They allow to include an additional if conditional after the primary condition associated to a branch. For example:

when (httpResponse) {
    is Success -> ...
    is HttpError if httpResponse.status >= 500 -> ...
    is HttpError -> ...
}

The code in a branch with a guard condition is executed only if both the primary condition and the if are verified. Also supported are if ... else guards.

Non-local break and continue can be used to break out or continue the execution of a loop from within a lambda executed inside the loop. For example:

fun processList(records: List<Int>): Boolean {
    for (record in list) {
        val variable = record.nullableValue() ?: run {
            log.warning("Record is null or invalid, continuing...")
            continue
        }
        if (variable == 0) return true
    }
    return false
}

Still on the syntax front, Kotlin 2.1.0 extends string interpolation to make it easier to use $ signs inside interpolated strings without needing to escape them. This can come in handy, for example, when generating JSON schemas and is enabled by using $$ as an interpolation prefix, as shown in the following example:

val KClass<*>.jsonSchema : String
    get() = $$"""
    {
      "$schema": "https://json-schema.org/draft/2020-12/schema",
      "$id": "https://example.com/product.schema.json",
      "$dynamicAnchor": "meta"
      "title": "$${simpleName ?: qualifiedName ?: "unknown"}",
      "type": "object"
    }
    """

Other new syntax features include the @SubclassOptInRequired annotation to require explicit opt-in to enable subclassing; improved overload resolution for functions with generic types; and improved exhaustiveness checks for when expressions with sealed classes.

The new syntax capabilities described here are still in preview and must be enabled at the compiler level if you want to use them.

The Kotlin 2.1.0 release also brings a more flexible K2 compiler with new configurable compiler checks, including for unused variables, unreachable code, defining a value and not using it, and so on. Conversely, K2 now supports silencing all warnings one by one.

K2 also brings an improved kapt plugin implementation. kapt is an annotation processor which enables using libraries like Dagger or Data Binding to generate/modify code based on textual annotations. While kapt is currently in maintenance mode and superseded by the Kotlin Symbol Processing API, the new version coming with Kotlin 2.1.0 provides improved performance for all current users.

Another area where Kotlin 2.1.0 brings significant changes is multiplatform programming, with support for using Swift API without using Objective-C headers, a new DSL to configure compiler options, and support to publish multiplatform libraries from any platform, including the previously excluded macOS.

Kotlin 2.1.0 may break existing code, so you'll want to check the official migration guide before updating your build script when using IntelliJ IDEA 2023.3 and Android Studio Iguana (2023.2.1) Canary 15.

About the Author

Rate this Article

Adoption
Style

BT