Category: Kotlin & KMP

  • REST Client Code Generation in Kotlin Multiplatform


    Von der Spec zum Client — auf allen Plattformen

    Wer heute eine mobile App baut, baut meistens zwei: eine für Android, eine für iOS. Und irgendwo dazwischen schreibt man denselben HTTP-Code zweimal. Kotlin Multiplatform verspricht, dieses Problem zu lösen, aber wie sieht das konkret aus, wenn es um REST Clients geht?

    Ich habe mir das anhand eines Beispiel-Projekts angeschaut, das gegen die öffentliche Test-API httpbin.org arbeitet. Hier sind meine Erkenntnisse.


    Der Ansatz: Spec-first

    Statt den Client von Hand zu schreiben, startet man mit einer OpenAPI YAML-Spec als einziger Source of Truth. Daraus generiert der OpenAPI Generator vollständigen Kotlin-Code:

    openapi-generator-cli generate 
      -i httpbin.yaml 
      -g kotlin 
      -o ./generated 
      --library multiplatform 
      --additional-properties=serializationLibrary=kotlinx_serialization
    

    Das Ergebnis: fertige Models, API-Klassen und Infrastruktur, ohne eine Zeile manuell zu schreiben.


    Der technische Stack

    Der generierte Code basiert auf zwei Bibliotheken, die beide vollständig KMP-kompatibel sind.

    Ktor Client übernimmt die HTTP-Kommunikation. Die eigentliche Engine ist plattformspezifisch, OkHttp auf Android, Darwin auf iOS, aber der gesamte API-Code darüber liegt in commonMain und läuft auf allen Plattformen identisch.

    kotlinx.serialization übernimmt die JSON-Deserialisierung. Hier liegt ein entscheidender Unterschied zu Java: Die Serializer werden nicht zur Laufzeit per Reflection erzeugt, sondern zur Compile-Zeit vom Kotlin Compiler Plugin generiert.

    // commonMain — läuft auf iOS, Android, JVM und JS
    @Serializable
    data class IpResponse(
        @SerialName("origin") val origin: String? = null
    )
    
    class HttpBinApi : ApiClient {
        suspend fun ipGet(): HttpResponse<IpResponse> =
            request(RequestConfig(RequestMethod.GET, "/ip"), EmptyContent, listOf()).wrap()
    }
    

    Warum keine dynamischen Stubs?

    In der Java/Spring-Welt gibt es elegante Lösungen wie Feign oder Spring HTTP Interface: Man schreibt nur ein Interface, Spring erzeugt den fertigen Client zur Laufzeit via Reflection und Dynamic Proxy. Kein generierter Code auf Disk, minimaler Aufwand.

    Bei KMP ist dieser Ansatz bewusst ausgeschlossen, und das hat einen guten Grund.

    iOS kennt keine JVM-Reflection. Kotlin Native, das Compilation-Target für iOS, kann zur Laufzeit keine Klassen inspizieren und keine Proxies erzeugen. Alles muss zur Compile-Zeit bekannt und aufgelöst sein. Das bedeutet etwas mehr Compile-Zeit, dafür echter plattformübergreifender Support. Derselbe generierte Client läuft auf iOS, Android, JVM und JavaScript, ohne Anpassungen.

    Reflection-basiert (Spring Feign):
    Interface → Runtime Proxy → HTTP Call
    ✅ Elegant   ❌ JVM only
    
    Compile-Zeit (KMP + OpenAPI Generator):
    YAML Spec → Generator → Kotlin Code → Compiler → Binary
    ✅ Mehr Setup   ✅ iOS + Android + JVM + JS
    

    Integration als Gradle Plugin

    Der sauberste Weg ist das Gradle Plugin, Codegen läuft automatisch als Teil des Builds:

    openApiGenerate {
        generatorName.set("kotlin")
        inputSpec.set("$rootDir/api/httpbin.yaml")
        outputDir.set("$buildDir/generated")
        configOptions.set(mapOf(
            "library" to "multiplatform",
            "serializationLibrary" to "kotlinx_serialization"
        ))
    }
    

    Ändert sich die API, wird die YAML angepasst, der Code neu generiert, und der Compiler zeigt sofort wo Anpassungen nötig sind. Kein manuelles Synchronisieren zwischen Client und Server.


    Was ist mit TypeScript?

    KMP deckt iOS, Android, JVM und JavaScript ab, aber kein TypeScript. Angular und React bleiben aussen vor. Die pragmatische Lösung: aus derselben YAML-Spec einen separaten TypeScript-Client generieren.

    # Kotlin KMP Client
    openapi-generator-cli generate -g kotlin --library multiplatform
    
    # TypeScript Client für Angular
    openapi-generator-cli generate -g typescript-angular
    
    # Spring Server
    openapi-generator-cli generate -g spring
    

    Ein Tool, eine Spec, alle Plattformen. Die YAML ist der Vertrag, alle Clients halten sich daran.


    Fazit

    Der Spec-first Ansatz mit KMP ist kein Kompromiss, sondern eine bewusste Entscheidung für Compile-Zeit-Sicherheit statt Runtime-Magie. Wer Android und iOS mit demselben HTTP-Client-Code bedienen will, kommt an Ktor und kotlinx.serialization nicht vorbei. Der OpenAPI Generator nimmt dabei die Routinearbeit ab.

    Das Beispiel-Repo mit vollständigem Code gegen httpbin.org: github.com/tkausch/KotlinRest


    Thomas Kausch — iOS & Kotlin Multiplatform Developer, Zürich

  • Sunday afternoon Problem: Lazy Sequences as a Dynamic Programming Primitive in Kotlin

    Dynamic programming is usually taught with mutable arrays and index arithmetic — Kotlin’s generateSequence and sequence { } let you express the same recurrences as infinite, lazily-evaluated streams.

     

    Background

    Classic dynamic programming (DP) involves filling a table bottom-up: allocate an array, seed the base case, loop and fill. It works, but the code exposes implementation details — array indexing, loop bounds, off-by-one risks — that have nothing to do with the recurrence relation you’re actually trying to express. The algorithm gets buried in bookkeeping.

    Kotlin’s Sequence type is lazy: elements are computed on demand, one at a time, only when a terminal operator (take, first, toList, etc.) pulls them. This maps naturally onto DP recurrences, which are also defined element-by-element from previous values. Instead of a mutable array you manage manually, you get a self-describing stream where each element is a function of earlier ones.

    How It Works

    generateSequence(seed) { previous -> next } produces an infinite sequence where each element is derived from its predecessor. For recurrences that depend on only one previous value (factorial, powers, running totals) this is sufficient. For recurrences that depend on two or more previous values — Fibonacci, tribonacci, path counts — you pass a Pair or data class as the state carrier, destructure it in the lambda, and let the sequence track the window for you.

    The sequence { } builder with yield / yieldAll is more flexible: the lambda is a coroutine, so you can write imperative-looking code that suspends at each yield without allocating the entire series upfront. This is useful when the recurrence has conditional branches or multiple yield points (think coin change variants or staircase problems with variable step sizes).

    Crucially, neither generator allocates more than O(window) memory regardless of how far you iterate — compared to a bottom-up DP table that allocates O(n) or O(n²) upfront. For problems where you only need the nth value, not the full table, this is a meaningful difference.

    Code

    Fibonacci — the textbook case

    // Classic mutable DP table — works, but hides the recurrence
    fun fibTable(n: Int): Long {
        val dp = LongArray(n + 1)
        dp[0] = 0; dp[1] = 1
        for (i in 2..n) dp[i] = dp[i - 1] + dp[i - 2]
        return dp[n]
    }
    
    // Lazy sequence — the recurrence IS the code
    val fibonacci: Sequence<Long> = generateSequence(Pair(0L, 1L)) { (a, b) ->
        Pair(b, a + b)          // slide the window forward
    }.map { it.first }          // extract the current value
    
    val fib10 = fibonacci.elementAt(10)  // 55
    val first20 = fibonacci.take(20).toList()
    

    Staircase problem — n steps, can climb 1 or 2 at a time

    // How many distinct ways to reach step n?
    // Recurrence: ways(n) = ways(n-1) + ways(n-2)
    // Identical structure to Fibonacci, different semantics
    
    val staircaseWays: Sequence<Long> = generateSequence(Pair(1L, 1L)) { (prev2, prev1) ->
        Pair(prev1, prev1 + prev2)
    }.map { it.first }
    
    println(staircaseWays.elementAt(5))   // 8  (ways to climb 5 steps)
    println(staircaseWays.elementAt(10))  // 89
    

    Coin change — minimum coins, using sequence { } for a richer recurrence

    // Build the DP table lazily — each element is min coins for amount i
    fun minCoinsSequence(coins: List<Int>): Sequence<Int> = sequence {
        val dp = mutableListOf(0)   // base case: 0 coins for amount 0
        yield(0)
    
        var amount = 1
        while (true) {
            val minCoins = coins
                .filter { it <= amount }
                .minOfOrNull { dp[amount - it] + 1 }
                ?: Int.MAX_VALUE    // amount unreachable
            dp.add(minCoins)
            yield(minCoins)
            amount++
        }
    }
    
    val coins = listOf(1, 5, 6, 9)
    val table = minCoinsSequence(coins).take(12).toList()
    // index = amount, value = min coins needed
    // [0, 1, 2, 3, 4, 1, 1, 2, 2, 1, 2, 2]
    println("Min coins for 11: ${table[11]}")  // 2  (9 + 1 + 1... wait: 6+5=11 → 2)
    

    Taking only what you need — O(1) memory for the nth value

    // No table allocated — just the sliding window of two longs
    fun nthFibonacci(n: Int): Long =
        generateSequence(Pair(0L, 1L)) { (a, b) -> Pair(b, a + b) }
            .elementAt(n)
            .first
    

    Trade-offs & Limitations

    The lazy sequence approach works cleanly for 1D recurrences with a fixed, small window. It does not naturally handle 2D DP tables (e.g. longest common subsequence, edit distance) where you need an entire previous row — for those, a mutable array is still the right tool. elementAt(n) on a sequence is O(n) traversal with no caching, so if you call it repeatedly for different values of n on the same sequence, you recompute from the start each time; memoize with toList() or take(n+1).last() instead. The sequence { } builder uses Kotlin coroutines internally, which adds a small overhead per yield — for tight inner loops on large n, benchmark against the array version before committing.

    My Take

    generateSequence is the cleanest way to express sliding-window DP recurrences in Kotlin — the state carrier pattern with Pair makes the recurrence relation explicit and eliminates index arithmetic entirely. For simple problems (Fibonacci, tribonacci, staircase variants), this is strictly better than a mutable array: less code, no off-by-one risk, and you only compute what you actually consume. For problems where you need random access into the table, or where the recurrence has 2D structure, sequences don’t help and a plain IntArray is fine. The real value is in treating DP not as “fill a table” but as “define a recurrence” — sequences make that framing natural in Kotlin.


    Tags: Kotlin, Functional Programming, Dynamic Programming, Sequences

  • How Kotlin’s Inline Functions Make Lambdas First-Class Citizens for Functional Programming

    Kotlin has always marketed itself as functional-friendly, but until the K2 compiler era, inline lambdas had a subtle second-class limitation that forced awkward workarounds in functional-style code.

    Background

    Functional programming in Kotlin relies heavily on higher-order functions and lambdas — map, filter, fold, scope functions like let and run, and custom operators. Most of these are declared inline, which means the compiler copies the lambda body into the call site to avoid the overhead of object allocation for each lambda invocation.

    The problem: before Kotlin 2.0 and the K2 compiler, break and continue statements inside lambdas passed to inline functions were outright illegal in loop contexts. This created a jarring inconsistency. You could use non-local return in an inline lambda to exit the enclosing function — but you couldn’t use break to exit the enclosing loop. Kotlin 2.1 fixed this with non-local break and continue (KT-1436), and Kotlin 2.0’s K2 compiler quietly unlocked another improvement: smarter smart-casting inside inline lambdas via the implicit callsInPlace contract.

    These two changes, taken together, close the last significant gap between inline lambdas and regular language constructs — and they have a direct, practical impact on how you write functional-style Kotlin.

    How It Works

    Non-local break and continue (Kotlin 2.1)

    Previously, the compiler treated break/continue as strictly local to the innermost loop. Inside an inline lambda, there was no enclosing loop from the lambda’s own scope, so the compiler rejected the statement entirely. Kotlin 2.1 extends the non-local jump mechanism — already used for non-local return — to handle break and continue as well. When the lambda is inlined, the compiler can see the enclosing loop at the call site and generate the correct bytecode jump instruction.

    This affects every inline function that takes a lambda: forEach, filter, let, apply, run, also, with, and any custom inline higher-order function you write.

    K2’s implicit callsInPlace contract

    The K2 compiler now treats inline functions as having an implicit callsInPlace contract, without requiring you to declare it manually via contract { }. This means the compiler knows the lambda runs exactly once, in place, and therefore cannot leak references to captured variables. As a result, smart casts now work correctly inside inline lambdas — a variable that was checked as non-null before the call site remains smart-cast inside the lambda body.

    Code

    Before Kotlin 2.1 — the workaround was ugly:

    // Pre-2.1: break inside forEach was a compile error
    // You had to abandon forEach entirely and use a raw for loop
    val items = listOf(1, 2, 3, 4, 5)
    var found: Int? = null
    for (item in items) {
        if (item == 3) {
            found = item
            break // only works in raw for-loop
        }
    }
    
    // Or use firstOrNull — fine for simple cases, but not composable
    val result = items.firstOrNull { it == 3 }

    Kotlin 2.1+ — inline lambda with non-local break:

    // Now works as expected — break exits the outer for-loop
    val items = listOf(1, 2, 3, 4, 5)
    for (item in items) {
        item.takeIf { it > 0 }?.let {
            if (it == 3) break  // non-local break: exits the for-loop
            println(it)
        }
    }
    // prints: 1, 2
    
    // Practical example: early exit from a processing pipeline inside a loop
    data class Order(val id: Int, val valid: Boolean, val amount: Double)
    
    val orders = listOf(
        Order(1, true,  120.0),
        Order(2, false,  50.0), // invalid — should abort entire batch
        Order(3, true,  200.0)
    )
    
    var batchTotal = 0.0
    for (order in orders) {
        order.takeIf { it.valid }?.also {
            batchTotal += it.amount
        } ?: break  // non-local break: abort on first invalid order
    }
    println(batchTotal) // 120.0 — stopped before Order(2)

    K2 smart-cast inside inline lambda — no more redundant checks:

    // Pre-K2: compiler didn't know the lambda ran in-place,
    // so the smart-cast on `user` was lost inside `run`
    var user: User? = fetchUser()
    if (user != null) {
        user.run {
            println(name) // Error in K1: Smart cast to 'User' is impossible
        }
    }
    
    // K2: implicit callsInPlace contract — smart cast flows into the lambda
    var user: User? = fetchUser()
    if (user != null) {
        user.run {
            println(name) // Works — compiler knows `run` calls the lambda in-place
            println(email.uppercase())
        }
    }

    Composing functional pipelines with Result — now cleaner with non-local flow:

    fun processOrders(orders: List<Order>): Double {
        var total = 0.0
        for (order in orders) {
            runCatching { validate(order) }
                .onSuccess { total += it.amount }
                .onFailure { break } // exits the loop — illegal before 2.1
        }
        return total
    }

    Trade-offs & Limitations

    Non-local break and continue only apply to inline functions — a lambda passed to a regular (non-inline) higher-order function still cannot use them, because the compiler cannot guarantee the lambda runs in the enclosing scope. This means you cannot use non-local flow control with standard library functions that happen to be non-inline, such as Sequence terminal operators or coroutine builders. The feature also interacts subtly with labeled returns: if you have nested inline calls, you need to be precise about which loop you are targeting, using labels where ambiguous. Finally, the K2 smart-cast improvements only apply when the compiler can verify the callsInPlace semantics — custom inline functions with complex branching may still require an explicit contract { } block.

    My Take

    These two features are not headline-grabbing, but they quietly remove one of the most annoying friction points in writing functional-style Kotlin. The non-local break/continue change is particularly meaningful for Android and KMP developers who mix functional pipelines with imperative loop structures — something that happens constantly in real codebases, not just tutorials. The K2 smart-cast improvement matters most in Kotlin Multiplatform shared code, where you cannot rely on platform-specific null-handling conventions and need the compiler to carry type information as far as possible. Both changes point in the same direction: Kotlin is making its functional programming model more consistent and less surprising, without forcing you into a pure-FP straitjacket. That pragmatic balance is exactly what makes Kotlin worth using in production.


    Tags: Kotlin, Functional Programming, K2 Compiler, KMP

  • Koog

    JetBrains Koog: A Kotlin-Native Agent Framework That Skips the Python Tax

    If your backend is Kotlin or Java and you want to add AI agents, you’ve been forced to either wrap a Python service or accept a framework that treats your language as a second-class citizen — until now.

    Background

    LangChain has become the de-facto standard for orchestrating LLM-powered workflows. It’s flexible, well-documented, and has a massive ecosystem. But it’s Python-first, and when you’re running a JVM backend — whether Spring Boot, Ktor, or Android — that creates real friction. You either embed a Python subprocess, call a separate microservice, or use LangChain4j, which is a community-maintained Java port that lags behind the original and lacks native Kotlin idioms.

    JetBrains announced Koog at KotlinConf 2025 to address exactly this gap. The stated goal: a Kotlin-native agent framework with the same depth LangChain has, but built from the ground up for the JVM ecosystem — with Kotlin Multiplatform as a first-class target. As of version 0.7.x, it’s production-capable and supports JVM, Android, iOS, JavaScript, and WebAssembly targets.

    How It Works

    Koog models an AI agent as a strategy graph: a directed graph of nodes where each node can invoke an LLM, execute a tool, branch on conditions, or run sub-graphs in parallel. You define this graph using a Kotlin DSL, and the runtime executes it, managing state, history, retries, and observability transparently.

    The core abstraction is the AIAgent, which wraps a strategy (a graph or a simpler functional sequence) and a set of tools. Tools are just annotated Kotlin functions — Koog uses Kotlin serialization to auto-generate the JSON descriptors that LLMs need to call them. No separate schema file, no boilerplate.

    State persistence is where Koog diverges most sharply from LangChain. Rather than just checkpointing message history, Koog persists the entire state machine at any graph node. This means a crashed agent can resume from the exact strategy step it was on — not just replay from the last stored message. Backends include local disk, S3, or any database, and the new RollbackToolRegistry in v0.5.0 can undo tool side effects when rolling back to a checkpoint.

    On the observability side, Koog ships with native OpenTelemetry exporters for Langfuse and W&B Weave. Every LLM request, tool call, and node transition is traced. In LangChain you’d typically wire this yourself via callbacks; in Koog it’s a one-liner install(OpenTelemetry) block on any agent.

    LangChain’s Python async model is built on asyncio. Koog’s async story is Kotlin coroutines: cancellation is structured, backpressure is idiomatic, and there’s no GIL. Parallel graph branches use a MapReduce-style API — launch branches with fork, transform results asynchronously, collect at the end.

    Code

    LangChain (Python) — defining a tool and wiring an agent:

    from langchain.tools import tool
    from langchain.agents import initialize_agent
    
    @tool
    def get_weather(city: str) -> str:
        """Returns current weather for a city."""
        return fetch_weather_api(city)
    
    agent = initialize_agent(
        tools=[get_weather],
        llm=ChatOpenAI(model="gpt-4o"),
        agent="openai-functions",
        verbose=True,
    )
    agent.run("What's the weather in Berlin?")

    Koog (Kotlin) — equivalent agent with typed tool:

    val weatherTool = tool(
        name = "get_weather",
        description = "Returns current weather for a city"
    ) { city: String ->
        fetchWeatherApi(city)  // any suspend fun in your codebase
    }
    
    val agent = AIAgent(
        promptMessage = "What's the weather in Berlin?",
        llmClient = OpenAILLMClient("gpt-4o"),
        tools = listOf(weatherTool),
        strategy = strategy("weather-agent") {
            val result = node { callLlm() }
            edge(result to finish())
        }
    )
    
    runBlocking { agent.run() }

    Adding persistence (Koog only — no LangChain equivalent in-framework):

    val agent = AIAgent(...) {
        install(Persistence) {
            storage = S3AgentStorage(bucket = "my-agents")
            // Agent state machine is checkpointed at every node transition
        }
        install(OpenTelemetry) {
            addLangfuseExporter(
                langfuseUrl = "https://cloud.langfuse.com",
                langfusePublicKey = System.getenv("LANGFUSE_KEY"),
                langfuseSecretKey = System.getenv("LANGFUSE_SECRET")
            )
        }
    }

    Parallel branches (MapReduce-style):

    strategy("parallel-research") {
        val search = parallelNode {
            listOf("topic A", "topic B", "topic C").map { query ->
                fork { callLlm(query) }  // launched concurrently
            }
        }
        val merge = node { summarize(search.results) }
        edge(search to merge)
        edge(merge to finish())
    }

    Trade-offs & Limitations

    Koog is still pre-1.0 (current: 0.7.x), and the API surface has shifted across releases — v0.3 to v0.5 introduced breaking changes to tool descriptors and the non-graph strategy API. If you’re building on it now, pin your version and treat minor bumps as potentially breaking. The Python/LangChain ecosystem has a two-year head start in community integrations, vector store connectors, and pre-built chain templates. Koog’s ecosystem is growing but thin by comparison. iOS support was added by a community contributor in v0.4.0 and is newer than the JVM path. The graph-based strategy DSL has a real learning curve if you’re used to LangChain’s chain-of-thought or LCEL (LangChain Expression Language) approach — it’s more explicit and more powerful, but also more verbose for simple cases.

    My Take

    Koog is the right call if your team already lives on the JVM and you want AI agents that fit into your existing Spring Boot or Ktor services without a Python sidecar. The state-machine persistence model is genuinely better than anything LangChain offers out of the box — it’s the difference between “replay from message history” and “resume exactly where you crashed.” The Kotlin Multiplatform angle is particularly interesting for teams like those building KMP libraries: you can run the same agent logic on JVM, Android, and iOS without forking. For teams already on Python with a mature LangChain setup, the switching cost isn’t worth it yet. But for greenfield JVM projects or anyone already using KMP, Koog removes what was the last real blocker to writing agents in Kotlin.


    Tags: Kotlin, AI Agents, KMP, JetBrains

  • Kotlin Multiplatform (KMP) and xcframework: Sharing Logic with iOS Without the Pain

    Writing shared business logic once and shipping it to both Android and iOS turns out to be far less painful than I expected.

    Background

    The premise of Kotlin Multiplatform (KMP) has always sounded attractive: define your data models, network layer, database access, and business logic once in Kotlin, then consume it natively on both Android and iOS. No JavaScript bridge, no WebView, no shared runtime — just compiled native code on each platform.

    The skeptic’s counterargument is usually “sure, but the integration is a mess.” For iOS especially, the assumption is that wiring a Kotlin library into an Xcode project will involve fighting Gradle, broken symlinks, and mysterious linker errors for a weekend before anything actually runs.

    Working on KotlinGameBench — a Kotlin framework featuring game logic with a minimax AI engine — gave me a concrete reason to actually test this. The game logic (board state, move validation, search algorithm) is pure business logic with no platform dependencies. A perfect candidate for sharing.

    How It Works

    KMP compiles shared Kotlin code into an xcframework — a bundle containing compiled binaries for multiple Apple architectures (arm64 for device, x86_64/arm64 for simulator). This is the standard Apple format for distributing precompiled libraries and Xcode knows exactly how to consume it.

    The Gradle configuration is straightforward. You declare your targets in build.gradle.kts:

    kotlin {
        iosArm64()
        iosSimulatorArm64()
    
        targets.withType<org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget> {
            binaries.framework {
                baseName = "GameBench"
            }
        }
    }

    Running ./gradlew assembleXCFramework produces a GameBench.xcframework directory. You drag it into Xcode under Frameworks, Libraries, and Embedded Content, set it to Embed & Sign, and you’re done. No CocoaPods required, no SPM manifest to maintain.

    The Kotlin compiler generates Objective-C headers for all public declarations in your shared module. These headers are what Xcode actually sees — Swift consumes them via the Objective-C bridge, which is fully automatic.

    Code

    On the Kotlin side, a shared data class and interface look like this:

    // Shared module — compiles to both Android and iOS
    data class ConnectMove(val column: Int, val player: Player) : Move
    
    interface SearchableBoard {
        fun makeMove(move: Move)
        fun undoMove(move: Move)
        fun evaluate(): Int
        fun isTerminal(): Boolean
        fun availableMoves(player: Player): List<Move>
    }

    The generated Objective-C header exposes ConnectMove as an @interface and SearchableBoard as a @protocol. Swift sees them as native types:

    import GameBench
    
    // Swift usage — no wrappers needed
    let board = ConnectBoard()
    let engine = SearchEngine()
    let bestMove = engine.getBestMove(board: board, player: .white, depth: 6)

    The naming convention follows Objective-C style — so Kotlin’s getBestMove(board:player:depth:) arrives in Swift with labeled parameters intact. It reads naturally.

    Trade-offs & Limitations

    The main friction point is that KMP generates Objective-C headers, not Swift. This means some Kotlin constructs don’t map cleanly: sealed classes arrive as abstract base classes with subclasses rather than Swift enums, Kotlin’s suspend functions require a compatibility layer (kotlinx-coroutines-native with @Throws annotations), and generics are often erased to id. The SKIE plugin by Touchlab addresses most of these — it post-processes the Kotlin compiler output to generate proper Swift-friendly APIs including real async/await support and Swift enums from sealed classes. It’s worth adding from the start rather than retrofitting later.

    My Take

    The xcframework integration story is genuinely solid. The part that surprised me most is how syntactically close Kotlin and Swift actually are — data classes vs structs, when vs switch, extension functions, named parameters — switching context between the two is far less jarring than switching between, say, Kotlin and TypeScript. The Objective-C interop layer is the only real rough edge, and SKIE largely papers over it. If your iOS app has any meaningful business logic — validation rules, state machines, parsing, algorithms — KMP is worth the setup cost. The break-even point is lower than you’d think.


    Tags: Kotlin, KotlinMultiplatform, iOS, Swift