---
name: kotlin-multiplatform-8193b6372745
description: >-
  Kotlin Multiplatform (KMP) is JetBrains' technology for sharing Kotlin code
  between Android, iOS, web, and desktop applications while keeping the UI
  native on each platform. Use when a user asks to set up a KMP shared module,
  share business logic, networking or a data layer between Android and iOS,
  write expect/actual declarations, use Ktor or SQLDelight in commonMain, write
  a shared ViewModel, test shared code, or migrate a KMP project to Android
  Gradle Plugin 9.
license: Apache-2.0
compatibility: "Kotlin 2.4 on JDK 17 or newer; AGP 9.4 needs Gradle 9.6 or newer (AGP 9.0 needs 9.1). The Android target needs the Android SDK and AGP 9; building or testing iOS targets needs macOS with Xcode."
metadata:
  author: terminal-skills
  version: 1.1.0
  category: development
  tags: "kotlin, kmp, cross-platform, mobile, ios"
  repository: https://github.com/JetBrains/kotlin
---

# Kotlin Multiplatform — Shared Business Logic for Mobile

## Overview

Kotlin Multiplatform (KMP) compiles one Kotlin codebase for Android, iOS, desktop (JVM) and web. Business logic, networking and the data layer live in a shared module; each platform keeps its own UI (or shares it too with Compose Multiplatform). Platform differences are isolated behind `expect`/`actual` declarations.

## Instructions

### Project Structure

Create the project with the Kotlin Multiplatform wizard in IntelliJ IDEA or Android Studio (New Project > Kotlin Multiplatform). Shared code and app entry points are separate modules:

```
tasklane/
├── shared/                              # Kotlin Multiplatform module (build.gradle.kts below)
│   └── src/
│       ├── commonMain/kotlin/           # Platform-independent code
│       ├── commonMain/sqldelight/       # .sq files (SQLDelight)
│       ├── androidMain/, iosMain/, jvmMain/   # actuals per platform (iosMain comes from the default hierarchy)
│       └── jvmTest/kotlin/              # Tests that run on any machine
├── androidApp/                          # Android app (Jetpack Compose), depends on :shared
└── iosApp/                              # Xcode project (SwiftUI), links the Shared framework
```

### Gradle Setup

```kotlin
// shared/build.gradle.kts
plugins {
    kotlin("multiplatform") version "2.4.20"
    kotlin("plugin.serialization") version "2.4.20"
    id("app.cash.sqldelight") version "2.4.0"
    id("com.android.kotlin.multiplatform.library") version "9.4.1"
}
kotlin {
    jvm()
    android {                       // replaces androidTarget() and the top-level android {} block
        namespace = "com.tasklane.shared"
        compileSdk = 36
        minSdk = 24
    }
    listOf(iosArm64(), iosSimulatorArm64()).forEach { target ->
        target.binaries.framework {
            baseName = "Shared"     // Swift: import Shared
            isStatic = true
        }
    }
    sourceSets {
        commonMain.dependencies {
            implementation("io.ktor:ktor-client-core:3.6.0")
            implementation("io.ktor:ktor-client-content-negotiation:3.6.0")
            implementation("io.ktor:ktor-serialization-kotlinx-json:3.6.0")
            implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
            implementation("app.cash.sqldelight:coroutines-extensions:2.4.0")
            implementation("org.jetbrains.androidx.lifecycle:lifecycle-viewmodel:2.11.0")
        }
        commonTest.dependencies {
            implementation(kotlin("test"))
            implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.11.0")
            implementation("io.ktor:ktor-client-mock:3.6.0")
        }
        // One HTTP engine and one SQLite driver per platform
        androidMain.dependencies { implementation("io.ktor:ktor-client-okhttp:3.6.0"); implementation("app.cash.sqldelight:android-driver:2.4.0") }
        jvmMain.dependencies { implementation("io.ktor:ktor-client-okhttp:3.6.0"); implementation("app.cash.sqldelight:sqlite-driver:2.4.0") }
        iosMain.dependencies { implementation("io.ktor:ktor-client-darwin:3.6.0"); implementation("app.cash.sqldelight:native-driver:2.4.0") }
    }
}
sqldelight { databases { create("TaskDatabase") { packageName.set("com.tasklane.db") } } }
```

Useful tasks: `./gradlew :shared:jvmTest` (shared tests on the JVM), `:shared:iosSimulatorArm64Test` (macOS only), `:shared:allTests`. Xcode builds the framework through a run-script phase that calls `./gradlew :shared:embedAndSignAppleFrameworkForXcode`.

### Local Database with SQLDelight

```sql
-- shared/src/commonMain/sqldelight/com/tasklane/db/Task.sq
-- SQLDelight generates TaskDatabase, TaskEntity and typed query functions from this file.
CREATE TABLE TaskEntity (
    id TEXT NOT NULL PRIMARY KEY,
    title TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'TODO',
    pending_sync INTEGER NOT NULL DEFAULT 0,
    created_at INTEGER NOT NULL
);
selectAll:
SELECT * FROM TaskEntity ORDER BY created_at DESC;
upsert:
INSERT OR REPLACE INTO TaskEntity(id, title, status, created_at) VALUES (?, ?, ?, ?);
markPendingSync:
UPDATE TaskEntity SET pending_sync = 1 WHERE id = ?;
```

### Platform-Specific Code with expect/actual

```kotlin
// shared/src/commonMain/kotlin/com/tasklane/shared/Platform.kt
// 'expect' declares what each platform must implement.
expect fun platformName(): String
expect class DriverFactory {
    fun createDriver(): SqlDriver
}
// shared/src/androidMain/kotlin/com/tasklane/shared/Platform.android.kt
actual fun platformName(): String = "Android ${android.os.Build.VERSION.SDK_INT}"
actual class DriverFactory(private val context: Context) {
    actual fun createDriver(): SqlDriver = AndroidSqliteDriver(TaskDatabase.Schema, context, "tasks.db")
}
// shared/src/iosMain/kotlin/com/tasklane/shared/Platform.ios.kt
actual fun platformName(): String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
actual class DriverFactory {
    actual fun createDriver(): SqlDriver = NativeSqliteDriver(TaskDatabase.Schema, "tasks.db")
}
// shared/src/jvmMain/kotlin/com/tasklane/shared/Platform.jvm.kt
actual fun platformName(): String = "JVM ${System.getProperty("java.version")}"
actual class DriverFactory {
    actual fun createDriver(): SqlDriver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY).also { TaskDatabase.Schema.create(it) }
}
```

Imports: `app.cash.sqldelight.db.SqlDriver`, `app.cash.sqldelight.driver.android.AndroidSqliteDriver`, `app.cash.sqldelight.driver.native.NativeSqliteDriver`, `app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver`, `platform.UIKit.UIDevice`.

### Networking with Ktor

```kotlin
// shared/src/commonMain/kotlin/com/tasklane/shared/TaskApi.kt
// (imports from io.ktor.client.*, io.ktor.http.*, kotlinx.serialization.* omitted)
@Serializable
data class TaskDto(val id: String, val title: String, val status: String, val createdAt: Long)

class TaskApi(baseUrl: String, authToken: String, engine: HttpClientEngine? = null) {
    private val config: HttpClientConfig<*>.() -> Unit = {
        install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) } // don't crash on extra API fields
        defaultRequest {
            url(baseUrl)
            bearerAuth(authToken)
            contentType(ContentType.Application.Json) // required for setBody(task)
        }
    }
    // Without an engine argument Ktor picks the one on the classpath: OkHttp on Android, Darwin on iOS
    private val client = if (engine != null) HttpClient(engine, config) else HttpClient(config)

    suspend fun fetchTasks(): List<TaskDto> = client.get("api/tasks").body()
    suspend fun createTask(task: TaskDto): TaskDto = client.post("api/tasks") { setBody(task) }.body()
}
```

### Shared Business Logic

```kotlin
// shared/src/commonMain/kotlin/com/tasklane/shared/TaskRepository.kt
// Runs on every target — write once, test once. Uses asFlow/mapToList from
// app.cash.sqldelight.coroutines and kotlin.time.Clock, kotlin.uuid.Uuid from the standard library.
class TaskRepository(private val api: TaskApi, db: TaskDatabase) {
    private val queries = db.taskQueries

    // Emits the cached list again whenever the table changes
    fun getTasks(): Flow<List<TaskEntity>> = queries.selectAll().asFlow().mapToList(Dispatchers.Default)

    // Pull the server state into the local cache
    suspend fun syncTasks() {
        val remote = api.fetchTasks()
        queries.transaction {
            remote.forEach { queries.upsert(it.id, it.title, it.status, it.createdAt) }
        }
    }

    // Save locally first; if the request fails, flag the row for a later sync
    suspend fun createTask(title: String): String {
        val task = TaskDto(Uuid.random().toString(), title, "TODO", Clock.System.now().toEpochMilliseconds())
        queries.upsert(task.id, task.title, task.status, task.createdAt)
        try { api.createTask(task) } catch (e: Exception) { queries.markPendingSync(task.id) }
        return task.id
    }
}
```

### ViewModel (Shared UI Logic)

```kotlin
// shared/src/commonMain/kotlin/com/tasklane/shared/TaskListViewModel.kt
// androidx.lifecycle.ViewModel is multiplatform; viewModelScope is cancelled when the ViewModel is cleared.
data class TaskListUiState(val tasks: List<TaskEntity> = emptyList(), val isLoading: Boolean = true, val error: String? = null)

class TaskListViewModel(private val repository: TaskRepository) : ViewModel() {
    private val _uiState = MutableStateFlow(TaskListUiState())
    val uiState: StateFlow<TaskListUiState> = _uiState.asStateFlow()
    init {
        repository.getTasks()
            .onEach { tasks -> _uiState.update { it.copy(tasks = tasks, isLoading = false) } }
            .launchIn(viewModelScope)
        refresh()
    }

    fun refresh() {
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            try { repository.syncTasks() } catch (e: Exception) { _uiState.update { it.copy(error = e.message) } }
            _uiState.update { it.copy(isLoading = false) }
        }
    }
    fun createTask(title: String) { viewModelScope.launch { repository.createTask(title) } }
}
```

## Examples

### Example 1: Test the shared repository without an emulator

**User request:** "Add a test for the sync logic in our shared module that I can run on CI without Android or iOS devices."

```kotlin
// shared/src/jvmTest/kotlin/com/tasklane/shared/TaskRepositoryTest.kt
class TaskRepositoryTest {
    private val engine = MockEngine { request ->
        assertEquals("Bearer test-token", request.headers[HttpHeaders.Authorization])
        respond(
            content = """[{"id":"t1","title":"Ship v2","status":"TODO","createdAt":1790000000000,"assignee":"mira"}]""",
            headers = headersOf(HttpHeaders.ContentType, "application/json"),
        )
    }

    @Test
    fun syncStoresRemoteTasks() = runTest {
        val db = TaskDatabase(DriverFactory().createDriver()) // in-memory SQLite on the JVM
        val repository = TaskRepository(TaskApi("https://api.tasklane.dev/", "test-token", engine), db)
        repository.syncTasks()
        assertEquals(listOf("Ship v2"), repository.getTasks().first().map { it.title })
    }
}
```

`./gradlew :shared:jvmTest` compiles commonMain and jvmMain, generates the SQLDelight code and ends with `BUILD SUCCESSFUL`; the report is in `shared/build/reports/tests/jvmTest/index.html`. The unknown `assignee` field is ignored because of `ignoreUnknownKeys`.

### Example 2: Fix the build after upgrading to Android Gradle Plugin 9

**User request:** "After bumping AGP to 9 the build fails: The 'com.android.library' (or 'com.android.application') plugin is not compatible with the 'org.jetbrains.kotlin.multiplatform' plugin since AGP 9.0."

```diff
 // shared/build.gradle.kts
 plugins {
     kotlin("multiplatform") version "2.4.20"
-    id("com.android.library") version "9.4.1"
+    id("com.android.kotlin.multiplatform.library") version "9.4.1"
 }
 kotlin {
-    androidTarget()
+    android {
+        namespace = "com.tasklane.shared"
+        compileSdk = 36
+        minSdk = 24
+    }
 }
-android {
-    namespace = "com.tasklane.shared"
-    compileSdk = 36
-    defaultConfig { minSdk = 24 }
-}
```

Then move `src/main` to `src/androidMain`, `src/test` and `src/androidUnitTest` to `src/androidHostTest`, `src/androidTest` and `src/androidInstrumentedTest` to `src/androidDeviceTest`. Android tests are off until `withHostTest {}` or `withDeviceTest {}` is added inside `android {}`. Keep the application itself (`com.android.application`, `MainActivity`) in a separate `androidApp` module that depends on `:shared`. `./gradlew :shared:tasks` now configures and lists `assembleAndroidMain`.

## Guidelines

1. **Share logic, not UI** — Share business logic, networking, data layer in Kotlin; keep UI native (Jetpack Compose on Android, SwiftUI on iOS)
2. **expect/actual for platform APIs** — Use it for file system, biometrics, notifications. Check the standard library first: `kotlin.uuid.Uuid` and `kotlin.time.Clock`/`Instant` are common code (kotlinx-datetime 0.8 no longer ships `Instant` and `Clock`). `expect class` is still Beta and warns unless `-Xexpect-actual-classes` is set; `expect fun` is stable, and a plain interface implemented per platform avoids the warning
3. **Ktor for HTTP** — Ktor is the standard multiplatform HTTP client; it uses OkHttp on Android and URLSession (the Darwin engine) on iOS
4. **SQLDelight for local DB** — SQLDelight generates type-safe Kotlin from SQL; each target needs its own driver dependency
5. **Kotlin Serialization** — Use `@Serializable` data classes; works across all platforms unlike Gson or Moshi
6. **Coroutines + Flow** — Both are multiplatform. From Swift a `suspend` function is called with a completion handler or `async`; a `Flow` has no Swift counterpart, so expose callbacks or add SKIE or KMP-NativeCoroutines
7. **Start with the shared module** — Build it with tests first (`jvmTest` needs no device); then wrap it with platform UIs. `viewModelScope` uses `Dispatchers.Main`, which a desktop JVM app gets from `kotlinx-coroutines-swing`
8. **Compose Multiplatform for UI** — If you want shared UI too, use Compose Multiplatform (covers Android, iOS, desktop, web)
9. **AGP 9** — `com.android.library` and `com.android.application` no longer work in a multiplatform module. The Android-KMP library plugin has a single variant: no build types, product flavors or `BuildConfig`
10. **iOS needs a Mac** — iOS targets compile and test only on macOS with Xcode; on other hosts Gradle disables them with a warning. `iosX64` (Intel simulators) is a Tier 3 target; use `iosSimulatorArm64`


---
Source attribution: TerminalSkills
Original project: https://github.com/TerminalSkills/skills/blob/3bfbf7f76459d89422eddc0e5f572ad0e6c393c9/skills/kotlin-multiplatform/SKILL.md
License: Apache-2.0
License information: https://www.apache.org/licenses/LICENSE-2.0
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to the Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by the Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding any notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   Copyright 2025 Terminal Skills

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.



# Mega AI Hub resource metadata

Creator / publisher: TerminalSkills
Original project: https://github.com/TerminalSkills/skills/blob/3bfbf7f76459d89422eddc0e5f572ad0e6c393c9/skills/kotlin-multiplatform/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering, Product Management
Roles: Backend Developer, Frontend Developer, Full-Stack Developer, Mobile Developer, Product Manager
Specialties: Cross Platform, Mobile
Tools: Jetbrains
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: c4112b9ea016dc420ed790d3c2b93f0377599b46794a9f39a77f5b90182c979b
