Kotlin Multiplatform Project Structure & Gradle
Core Rules
- Apply the KMP plugin with
kotlin("multiplatform")(org.jetbrains.kotlin.multiplatform); version matches the Kotlin release (current stable:2.4.21). - Declare explicit targets inside
kotlin {}(e.g.,jvm(),iosArm64(),iosSimulatorArm64(),js { browser() },wasmJs { browser() },androidLibrary {}). Never use removed Apple shortcuts (ios(),watchos(),tvos()) orpresets/fromPreset. - Keep
commonMainplatform-agnostic: Only Kotlin stdlib, common code, and multiplatform libraries supporting all declared targets compile incommonMain. - Prefer the default hierarchy template: Let KGP auto-create intermediate source sets (
iosMain,appleMain,nativeMain,webMain, and*Testcounterparts) with type-safe accessors. - Separate app entry points from shared code: Put Android (
androidApp), Desktop (desktopApp), and Web (webApp) entry points in dedicated modules. This is mandatory for AGP 9+. - Use
compilerOptions {}at extension, target, or task level. Do not use deprecatedkotlinOptions {}(deprecated in 2.2.0). - Never apply
withJava()or Gradlejava/java-library/applicationplugins in a KMP module (Java source sets are created by default since Kotlin 2.1.20;withJava()fails on Gradle 9.0). - Never ship multiple Kotlin/Native frameworks in one iOS app; aggregate feature modules into a single umbrella module and export them into one umbrella framework.
- Keep
expectandactualin the exact same package, and prefer commoninterfaces (wired via DI, entry points, orexpect funfactories) over Betaexpect class.
Decision Trees
1. Source Set Hierarchy: Default Template vs. Custom
Need an intermediate source set?
├── Already in the default template (iosMain, appleMain, nativeMain, webMain, etc.)?
│ └── YES → Declare explicit targets only; do NOT call dependsOn(). Use type-safe accessors.
├── Need an extra group not in the default template (e.g., jvmAndMacos)?
│ └── YES → Call applyDefaultHierarchyTemplate() explicitly, create the source set with
│ `by creating { dependsOn(commonMain.get()) }`, and connect target source sets to it.
└── Need to redefine built-in template edges (e.g., nativeMain = desktop-only)?
└── YES → Either choose a custom name (e.g., myDesktopMain) OR set
`kotlin.mpp.applyDefaultHierarchyTemplate=false` in gradle.properties and wire manually.
Constraint: Kotlin does not support a shared intermediate source set combining multiple JVM targets, JVM + Android only, or multiple JS targets. Also never call
dependsOn()oncommonMainorcommonTest(error since 1.9.20).
2. Module & Repository Layout
Structuring a KMP project?
├── All platforms share UI (Compose Multiplatform) + business logic?
│ └── Use separate entry point modules (androidApp, desktopApp, webApp, iosApp) + one `shared` module.
├── Any platform uses native UI (e.g., SwiftUI on iOS)?
│ └── Split shared code into `sharedLogic` (no Compose plugins) + `sharedUI` (Compose + composeResources).
├── Includes a backend server sharing models/validation?
│ └── Use `app/` (entry points + client shared modules), `server/`, and `core/`.
└── Scaling to multiple shared feature modules on iOS?
└── Add an umbrella module with `api(project(":feature"))` + `framework { export(project(":feature")) }`.
3. Dependency Placement
Where to declare a dependency?
├── Multiplatform library used everywhere (Ktor, Coroutines, Koin, kotlin("test"))?
│ └── Add to `commonMain.dependencies {}` (or `commonTest.dependencies {}`) using Gradle version catalogs.
├── Multiplatform library needed on a subset of targets (e.g., SQLDelight native driver)?
│ └── Add the common/root coordinate (NOT target-suffixed) to the intermediate source set (`iosMain.dependencies {}`).
├── Android-specific dependency?
│ └── Add to `androidMain.dependencies {}` (or `androidRuntimeClasspath` on `com.android.kotlin.multiplatform.library`;
│ avoid standalone top-level `dependencies {}` except for legacy `kapt` placed after `kotlin { android {} }`).
└── iOS-specific native dependency?
├── Apple SDK (Foundation, UIKit, etc.) → Prebuilt; import directly in `iosMain`.
├── C / Obj-C / `@objc` Swift library or framework → Configure `cinterops` + `.def` file + `linkerOpts`, or use CocoaPods `pod()`.
└── Pure Swift library (no `@objc`) → Not directly supported by cinterop/CocoaPods; bridge from Swift in `iosApp` via DI/interfaces.
4. Accessing Platform-Specific APIs
Need platform-specific functionality?
├── Does a maintained KMP library exist on klibs.io (or via https://api.klibs.io/mcp)?
│ └── YES → Use the library instead of writing platform code.
├── Is it a simple stateless function/property (e.g., randomUUID())?
│ └── YES → Use `expect fun` / `expect val` in `commonMain` + `actual` in platform/intermediate source sets.
├── Is it a service with state, multiple implementations, or test fakes?
│ └── YES → Define a common `interface` in `commonMain` and provide implementations via:
│ 1. Existing DI framework (e.g., Koin `expect val platformModule: Module`), OR
│ 2. Platform app entry points (zero `expect`/`actual`), OR
│ 3. An `expect fun` factory returning the interface.
└── Must it inherit from an existing platform base class or be a framework abstract base?
└── YES → Use `expect class` (Beta; suppress warning with `freeCompilerArgs.add("-Xexpect-actual-classes")`)
or `actual typealias` to map directly to an existing platform class.
5. AGP 9 Migration Path
Upgrading a KMP + Android project to AGP 9.0+?
├── Need an immediate stopgap before refactoring?
│ └── Set `android.enableLegacyVariantApi=true` in gradle.properties (temporary; removed in AGP 10).
└── Performing the full migration (required before AGP 10):
1. Extract Android app entry point (`MainActivity`, `android {}`, `applicationId`) into `androidApp`
while keeping all `actual` declarations in the shared module's `androidMain`.
2. In the shared module, replace `com.android.application` / `com.android.library` + `androidTarget {}`
with `com.android.kotlin.multiplatform.library` and `kotlin.androidLibrary {}`.
3. Replace `debugImplementation(...)` in the shared module with `androidRuntimeClasspath(...)`
and enable `androidResources { enable = true }` if using Compose resources.
4. Bump AGP to `9.0.0+` and Gradle wrapper to `9.1.0+`.
5. Remove `org.jetbrains.kotlin.android` from `androidApp` (AGP 9 has built-in Kotlin).
6. Ensure `androidLibrary.namespace` differs from `androidApp`'s `android.namespace`.
6. Native Binaries & Compilations
- Default output: Kotlin/Native produces
*.klibonly. Addbinaries { executable() / sharedLib() / staticLib() / framework() }to emit final binaries. - Exporting modules to iOS: Declare dependencies as
api(...)and explicitly callexport(...)insideframework {}. AvoidtransitiveExport = true. - Distributing Apple frameworks: Prefer
XCFramework()(assembleXCFramework/assemble<Name>ReleaseXCFramework) overFatFrameworkTask. CustomizeInfo.plistwithbinaryOption("bundleId", ...). - Custom compilations (e.g.,
integrationTest): CallassociateWith(main)to inheritmain's classpath andinternalvisibility, and register atestRuns.create(...).
Reference Index
Load the relevant reference file when working on a specific area:
- Project Structure & Hierarchy: Common code constraints, Apple device/simulator targets, full default hierarchy template, manual
dependsOnrules, valid target combinations, source-set-to-source-set resolution, and*Main/*Testversion alignment. - Modules & Repo Architecture: Step-by-step extraction of
androidApp,desktopApp,webApp,sharedLogic/sharedUI, Xcode Build Phase updates, why umbrella frameworks are required on iOS, monorepo vs multi-repo layouts, and local vs remote (SwiftPM/KMMBridge) workflows. - Dependencies: Version catalogs,
kotlin-stdlib,kotlin("test"),kotlinx, multiplatform project deps, Android source-set deps, iOScinterop(.deffiles for C/Obj-C libraries & frameworks) and CocoaPodspod(), andklibs.io/ MCP discovery. - Platform APIs &
expect/actual: Completeexpect/actualrules and examples (functions, properties, objects, interfaces, DI with Koin, entry points, Betaexpect class,actual typealias, expanded visibility, extra enum entries requiringelse, and@OptionalExpectationannotations). - Compilations & Native Binaries: 3-level
compilerOptions, custom compilations withassociateWith, JVM/Android/cinterop compilation details,languageSettingsconsistency, Gradle Isolated Projects,binaries {}declarations & getters,export(),FatFrameworkTask,XCFramework, andInfo.plistbinaryOptions. - Gradle DSL Reference: Complete
kotlin {}DSL reference for all targets (jvm,js,wasmJs,wasmWasi, Native, Android),browser {}/nodejs {},binaries {}(includingdisableNativeCache),cinterops {},sourceSets {},compilations {},compilerOptions {}, experimental top-levelkotlin.dependencies {}, andlanguageSettings {}. - AGP 9 & Android Migration: Detailed AGP 9 migration walkthrough (
androidAppextraction,com.android.kotlin.multiplatform.library,androidRuntimeClasspath, Gradle 9.1+, built-in Kotlin) and Android source set layout v2 (androidUnitTest,androidInstrumentedTest,AndroidManifest.xmlpaths,invokeWhenCreated). - Compatibility & Tooling: Kotlin 1.9.20–2.4.21 vs Gradle/AGP/Xcode compatibility matrix, breaking changes & deprecation cycles, Kotlin Toolchain (Alpha) CLI (
kotlin new/run/publish testflight,module.yaml), and KMP IDE plugin requirements (K2 mode, IDE versions).