CommunityCoding & Developmentgithub.com

jayvijaygohil/kmp-project-structure-gradle

Configure and structure Kotlin Multiplatform (KMP) Gradle projects, targets, source set hierarchies, dependencies, modular layouts, platform APIs, compilations, native binaries, and AGP 9 migrations. Use when setting up or modifying `build.gradle.kts` with `org.jetbrains.kotlin.multiplatform`, configuring `sourceSets` or `dependsOn`, adding multiplatform/Android/iOS (`cinterop`/CocoaPods) dependencies or searching `klibs.io`, extracting `androidApp`/`desktopApp`/`webApp` or `sharedLogic`/`sharedUI` modules and iOS umbrella frameworks, designing `expect`/`actual` vs interfaces/DI, configuring `compilerOptions` or custom compilations, building Kotlin/Native executables/frameworks/XCFrameworks, using Kotlin Toolchain (`module.yaml`), migrating to AGP 9 (`com.android.kotlin.multiplatform.library`) or Android source set layout v2, or resolving KMP/Gradle/AGP/Xcode compatibility and deprecation errors.

What is kmp-project-structure-gradle?

kmp-project-structure-gradle is a Claude Code agent skill that configure and structure Kotlin Multiplatform (KMP) Gradle projects, targets, source set hierarchies, dependencies, modular layouts, platform APIs, compilations, native binaries, and AGP 9 migrations. Use when setting up or modifying `build.gradle.kts` with `org.jetbrains.kotlin.multiplatform`, configuring `sourceSets` or `dependsOn`, adding multiplatform/Android/iOS (`cinterop`/CocoaPods) dependencies or searching `klibs.io`, extracting `androidApp`/`desktopApp`/`webApp` or `sharedLogic`/`sharedUI` modules and iOS umbrella frameworks, designing `expect`/`actual` vs interfaces/DI, configuring `compilerOptions` or custom compilations, building Kotlin/Native executables/frameworks/XCFrameworks, using Kotlin Toolchain (`module.yaml`), migrating to AGP 9 (`com.android.kotlin.multiplatform.library`) or Android source set layout v2, or resolving KMP/Gradle/AGP/Xcode compatibility and deprecation errors.

Works with~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/jayvijaygohil/kmp-agent-skills/tree/HEAD/skills/kmp-project-structure-gradle

Installed? Explore more Coding & Development skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Ask in your favorite AI

Open a new chat with this agent skill pre-loaded.

Documentation

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()) or presets / fromPreset.
  • Keep commonMain platform-agnostic: Only Kotlin stdlib, common code, and multiplatform libraries supporting all declared targets compile in commonMain.
  • Prefer the default hierarchy template: Let KGP auto-create intermediate source sets (iosMain, appleMain, nativeMain, webMain, and *Test counterparts) 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 deprecated kotlinOptions {} (deprecated in 2.2.0).
  • Never apply withJava() or Gradle java/java-library/application plugins 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 expect and actual in the exact same package, and prefer common interfaces (wired via DI, entry points, or expect fun factories) over Beta expect 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() on commonMain or commonTest (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 *.klib only. Add binaries { executable() / sharedLib() / staticLib() / framework() } to emit final binaries.
  • Exporting modules to iOS: Declare dependencies as api(...) and explicitly call export(...) inside framework {}. Avoid transitiveExport = true.
  • Distributing Apple frameworks: Prefer XCFramework() (assembleXCFramework / assemble<Name>ReleaseXCFramework) over FatFrameworkTask. Customize Info.plist with binaryOption("bundleId", ...).
  • Custom compilations (e.g., integrationTest): Call associateWith(main) to inherit main's classpath and internal visibility, and register a testRuns.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 dependsOn rules, valid target combinations, source-set-to-source-set resolution, and *Main/*Test version 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, iOS cinterop (.def files for C/Obj-C libraries & frameworks) and CocoaPods pod(), and klibs.io / MCP discovery.
  • Platform APIs & expect/actual: Complete expect/actual rules and examples (functions, properties, objects, interfaces, DI with Koin, entry points, Beta expect class, actual typealias, expanded visibility, extra enum entries requiring else, and @OptionalExpectation annotations).
  • Compilations & Native Binaries: 3-level compilerOptions, custom compilations with associateWith, JVM/Android/cinterop compilation details, languageSettings consistency, Gradle Isolated Projects, binaries {} declarations & getters, export(), FatFrameworkTask, XCFramework, and Info.plist binaryOptions.
  • Gradle DSL Reference: Complete kotlin {} DSL reference for all targets (jvm, js, wasmJs, wasmWasi, Native, Android), browser {}/nodejs {}, binaries {} (including disableNativeCache), cinterops {}, sourceSets {}, compilations {}, compilerOptions {}, experimental top-level kotlin.dependencies {}, and languageSettings {}.
  • AGP 9 & Android Migration: Detailed AGP 9 migration walkthrough (androidApp extraction, com.android.kotlin.multiplatform.library, androidRuntimeClasspath, Gradle 9.1+, built-in Kotlin) and Android source set layout v2 (androidUnitTest, androidInstrumentedTest, AndroidManifest.xml paths, 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).

Individual skills in this repo

This repo contains 1 individual skill — each has its own dedicated page.

Related Skills