Kotlin 2.4 Deep Dive: Multiplatform Interoperability and Standard Library Evolution

Kotlin · Release 2.4

Kotlin 2.4 Deep Dive: Multiplatform Interoperability and Standard Library Evolution

kotlinKotlinRelease2.4.20Programming Languages

Sources:GitHub Releases + 官方博客 + HN

The Kotlin team officially released Kotlin 2.4.20 on September 7, 2026. This release promotes invokedynamic compilation of when expressions on the JVM to stable, while delivering substantial upgrades across the standard library, Kotlin/Native, and Kotlin/Wasm. Below is a detailed breakdown of the key highlights.

Stable invokedynamic Compilation for when Expressions

Kotlin 2.2.20 originally introduced experimental support for compiling when expressions using invokedynamic on JVM 21 and newer. After multiple iterations of polish and optimization, this feature has officially graduated to stable in Kotlin 2.4.20 and is now enabled by default. This enhancement significantly reduces bytecode footprint and accelerates pattern matching execution.

New Functions for Collection Element Equality and Uniqueness

In earlier Kotlin versions, determining whether all elements in a collection are identical or entirely distinct often required verbose and suboptimal boilerplate. To solve this, Kotlin 2.4.20 introduces four experimental functions to the standard library: allDistinct(), allDistinctBy(), allEqual(), and allEqualBy().

Like other collection operations, these functions compare elements using structural equality (equals()) and work across collections, sequences, and arrays. As an experimental feature, usage requires the @OptIn(ExperimentalStdlibApi::class) annotation.

Official example:

@OptIn(ExperimentalStdlibApi::class)
fun main() {
    data class Response(
        val participantId: String,
        val answer: String,
        val responseDate: String
    )

    val responses = listOf(
        Response("P001", "Yes", "2026-07-21"),
        Response("P002", "Maybe", "2026-07-21"),
        Response("P003", "No", "2026-07-21")
    )

    // Check whether all participants submitted the same answer
    println(responses.allEqualBy { it.answer })
    // false

    // Check whether there are any duplicate participants
    println(responses.allDistinctBy { it.participantId })
    // true

    // Check whether all responses were submitted on the same date
    println(responses.allEqualBy { it.responseDate })
    // true

    val answers = responses.map { it.answer }

    // Check whether all answers are identical
    println(answers.allEqual())
    // false

    // Check whether all answers are completely distinct
    println(answers.allDistinct())
    // true
}

New Overloads for kotlin.test Assertion Functions

Kotlin 2.4.20 introduces new function overloads for common assertion functions in the kotlin.test package, including assertTrue(), assertEquals(), assertSame(), and assertContains().

Previously, assertion functions only accepted pre-formatted string error messages, constructing the string even when the assertion passed. The new overloads accept a lambda that lazily evaluates and builds the error message only when an assertion fails.

This aligns the API style with JUnit 5 and delivers noticeable performance gains, especially for projects using compiler plugins like Power-assert to generate rich error diagnostic messages.

Official example:

import kotlin.test.ExperimentalKotlinTestApi
import kotlin.test.assertEquals
import kotlin.test.assertTrue

@OptIn(ExperimentalKotlinTestApi::class)
fun testValues(actual: Int, expected: Int, items: List<String>) {
    // The error message is constructed only if the assertion fails
    assertTrue(actual > 0) { "Expected a positive value but got $actual" }

    // Avoid unnecessary list formatting unless the assertion fails
    assertEquals(expected, actual) { "Unexpected value for items: ${items.joinToString()}" }
}

Support for Coroutine Stack Trace Recovery

Kotlin 2.4.20 adds the StackTraceRecoverable interface to the standard library. This is a practical, low-level experimental improvement that significantly tightens integration between the core language and the kotlinx.coroutines library.

When debugging asynchronous code, exceptions rethrown across coroutine boundaries often lose valuable context; stack trace recovery reconstructs the asynchronous stack to reveal the true origin of an error. If a custom exception class requires mandatory constructor parameters (such as a source code line number), it can simply implement StackTraceRecoverable and override copyForStackTraceRecovery(). This allows libraries and applications to define recovery rules without adding an explicit dependency on kotlinx.coroutines.

Official example:

import kotlin.coroutines.ExperimentalStdlibCoroutineSupportApi
import kotlin.coroutines.debug.StackTraceRecoverable

@OptIn(ExperimentalStdlibCoroutineSupportApi::class)
class FileEditException
private constructor(
    val line: Int,
    private val detail: String,
    cause: Throwable?,
) : IllegalStateException("When editing line $line: $detail", cause),
    StackTraceRecoverable<FileEditException> {

    constructor(line: Int, detail: String) : this(line, detail, null)

    override fun copyForStackTraceRecovery(): FileEditException =
        FileEditException(line, detail, this)
}

New Swift Export Features

Kotlin/Native continues to deepen its cross-platform interoperability in this release, delivering two major capabilities for Swift export:

  1. Sealed Classes Support: Kotlin sealed class hierarchies are now natively mapped to Swift enumerations (enum). This allows Swift developers in Xcode to write exhaustive switch statements with full autocompletion, eliminating the need to hardcode a fallback default case.
  2. Cross-Language Inheritance: Developers can now define interfaces and base classes in Kotlin, implement them in Swift using pure Swift libraries, and pass those Swift objects back to Kotlin. This reverse-import model provides immense architectural flexibility for hybrid applications.

Official example (sealed class support):

// Kotlin side
sealed interface Shape
class Circle : Shape { override fun toString(): String = "Circle" }
class Rectangle : Shape { override fun toString(): String = "Rectangle" }
fun createCircle(): Shape = Circle()
// Swift side
let shape = createCircle()

let name = switch shape.sealedType() {
    case let .circle(type): "It's a \(type.value)"
    case let .rectangle(type): "It's a \(type.value)"
}
// name == "It's a Circle"

New Compilation Modes for Kotlin/Wasm

Previously, the Kotlin/Wasm compiler supported only monolithic compilation (monolith), bundling the entire project and its dependencies together to maximize dead code elimination and achieve minimal output binary sizes. Kotlin 2.4.20 introduces multi-module compilation modes for Kotlin/Wasm, configurable via gradle.properties:

  • monolith (default): Whole-program compilation that eliminates unreachable declarations and applies global optimizations.
  • multimodule-open-world: Compiles each module independently without cross-module optimizations, producing separate binaries to substantially speed up incremental builds during development.
  • multimodule-closed-world: Processes all modules in a single invocation, stripping unreachable declarations and optimizing each Wasm binary individually.

For development workflows, setting kotlin.wasm.compilationMode=multimodule-closed-world-only-in-dev is recommended to reduce rebuild times during day-to-day coding while preserving optimal production binary sizes.

Breaking Changes and Deprecations

Before upgrading to Kotlin 2.4.20, review the following breaking changes and deprecations:

  • Apple watchOS 32-bit Targets Deprecated: Following Apple’s discontinuation of 32-bit watchOS support, the watchosArm32 target in Kotlin/Native is now deprecated and scheduled for complete removal in Kotlin 2.5.0.
  • AtomicFU Restrictions in Inline Functions: The compiler now strictly prohibits the use of AtomicFU atomic operations within public inline functions or cross-file internal inline functions.
  • Webpack import.meta Behavior Change: Kotlin 2.4.20 updates Webpack to version 5.108.1. The updated Webpack no longer ignores import.meta, causing CommonJS-compatible code containing this token to be parsed strictly as ES modules, which may trigger bundling errors.
  • Deprecation of wasmExports in Kotlin/Wasm: The generated JavaScript wasmExports API is now deprecated. Except for wasmExports.memory, which remains temporarily accessible, the compiler no longer permits accessing other exported declarations.

Upgrade Recommendations

DimensionRecommendation
Who should upgradeAll Kotlin developers, particularly those heavily relying on multiplatform interoperability (Native, Wasm, JS) or seeking improved assertion performance in test suites.
When to upgradeImmediate upgrade is recommended. Ensure your IDE (IntelliJ IDEA or Android Studio) is updated to the latest version, then update the Kotlin version to 2.4.20 in your build scripts.
Key considerationsMigrate off watchosArm32 promptly if your project targets legacy watchOS devices. For JS and Wasm projects, check whether the Webpack 5.108.1 upgrade triggers module parsing issues related to import.meta and adjust configurations accordingly.

References