Configuring your first Kotlin Multiplatform project: Gradle, source sets and expect/actual
A Kotlin Multiplatform project starts well when a single command is enough to compile the shared logic for all platforms, and starts badly when Gradle reports targets that cannot find their dependencies. The quickest way to avoid the second situation is not to write the configuration by hand from scratch: the official generator at kmp.jetbrains.com (or the IDE's Kotlin Multiplatform plugin) produces a project that compiles, and your job is to understand every line it contains so you can change it without breaking it. This article walks through that project in seven steps.
There are three prerequisites: an IDE with the Kotlin Multiplatform plugin (Android Studio or IntelliJ IDEA), a recent JDK - the examples compile for JVM 17 - and, only if you want to build the iOS app, a Mac with Xcode. On this machine Kotlin and Gradle are not installed and I downloaded nothing: no block was compiled or run. They are schemas checked against the official documentation (listed in the Sources); the library versions, instead, were checked with an HTTP request to Maven Central, which means they exist, but they are not necessarily the latest.
Step 1: create the project and recognise its shape
The generator asks for the name, the package and the platforms (Android, iOS, desktop, server, Web), and hands you an archive to open in the IDE. The most important choice is whether the UI will be shared with Compose Multiplatform or native: it changes the organisation of the modules, not the logic module. For the basics of this series the answer is "native UI", so the shared module contains only logic.
my-kmp-app/
├── shared/ # shared logic module
│ ├── src/commonMain/kotlin/
│ ├── src/commonTest/kotlin/
│ ├── src/androidMain/kotlin/
│ ├── src/iosMain/kotlin/
│ ├── src/desktopMain/kotlin/
│ └── build.gradle.kts
├── androidApp/ # Android app that uses :shared
├── iosApp/ # Xcode project that imports the framework
├── gradle/libs.versions.toml # version catalog
├── build.gradle.kts # root: declares plugins without applying them
└── settings.gradle.kts # includes :shared and :androidApp
The rule to fix in your mind is that shared is a library, not an app: it has no entry point. The apps (androidApp and iosApp) are thin, they contain the startup and the interface, and they import shared. If you see business logic inside androidApp, you are on the wrong track: that code will never be shared with iOS.
Step 2: the version catalog
The file gradle/libs.versions.toml is Gradle's version catalog: a single place to declare versions, libraries and plugins, which the build scripts then reference as libs.ktor.client.core. The concrete advantage: updating Ktor means changing one number, not hunting for the string in five files, and a version shared by three libraries of the same project cannot drift apart.
# gradle/libs.versions.toml - schema to adapt, not executed
[versions]
kotlin = "2.0.20"
agp = "8.6.1"
coroutines = "1.9.0"
serialization = "1.7.3"
ktor = "2.3.12"
sqldelight = "2.0.2"
koin = "3.5.6"
datetime = "0.6.1"
[libraries]
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" }
serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" }
datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "datetime" }
ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }
ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }
sqldelight-runtime = { module = "app.cash.sqldelight:runtime", version.ref = "sqldelight" }
sqldelight-android = { module = "app.cash.sqldelight:android-driver", version.ref = "sqldelight" }
sqldelight-native = { module = "app.cash.sqldelight:native-driver", version.ref = "sqldelight" }
sqldelight-sqlite = { module = "app.cash.sqldelight:sqlite-driver", version.ref = "sqldelight" }
koin-core = { module = "io.insert-koin:koin-core", version.ref = "koin" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
android-library = { id = "com.android.library", version.ref = "agp" }
kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
sqldelight = { id = "app.cash.sqldelight", version.ref = "sqldelight" }
Each [libraries] entry has the form module + version.ref: the module is the Maven coordinate (group:artifact) and version.ref points to a key in [versions]. The hyphen in the name becomes a dot on access (ktor-client-core → libs.ktor.client.core). The pair that must stay aligned is kotlin and agp: each version of the Kotlin plugin declares the Android Gradle Plugin versions it supports, and a combination outside the list produces warnings or build errors. The versions written here exist on Maven Central and on Google's repository, but always check the compatibility table before updating them.
Step 3: the build script of the shared module
This is the file where you decide which platforms to compile for and which libraries each one depends on. The kotlin { } block declares the targets; sourceSets { } attaches the dependencies to the right level of the hierarchy. This is the version for AGP 8.x.
// shared/build.gradle.kts - schema to adapt, not executed (AGP 8.x)
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
alias(libs.plugins.kotlin.multiplatform)
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.sqldelight)
}
kotlin {
androidTarget {
compilerOptions { jvmTarget.set(JvmTarget.JVM_17) }
}
listOf(iosArm64(), iosSimulatorArm64()).forEach { target ->
target.binaries.framework {
baseName = "Shared"
isStatic = true
}
}
jvm("desktop")
sourceSets {
commonMain.dependencies {
implementation(libs.coroutines.core)
implementation(libs.serialization.json)
implementation(libs.datetime)
implementation(libs.ktor.client.core)
implementation(libs.sqldelight.runtime)
implementation(libs.koin.core)
}
commonTest.dependencies {
implementation(libs.kotlin.test)
}
androidMain.dependencies {
implementation(libs.ktor.client.okhttp)
implementation(libs.sqldelight.android)
}
iosMain.dependencies {
implementation(libs.ktor.client.darwin)
implementation(libs.sqldelight.native)
}
val desktopMain by getting
desktopMain.dependencies {
implementation(libs.ktor.client.okhttp)
implementation(libs.sqldelight.sqlite)
}
}
}
android {
namespace = "com.example.mykmpapp.shared"
compileSdk = 35
defaultConfig { minSdk = 26 }
}
sqldelight {
databases {
create("AppDatabase") { packageName.set("com.example.mykmpapp.db") }
}
}
Four points deserve attention. First: compilerOptions { jvmTarget.set(...) } replaces the old, deprecated kotlinOptions. Second: isStatic = true produces a static framework, which usually simplifies integration in Xcode; it is a choice, not an obligation. Third, and the most important: there is no dependsOn. By listing iosArm64() and iosSimulatorArm64(), the plugin creates the intermediate source sets apple, ios and native on its own (the default hierarchy template), and that is why you can write iosMain.dependencies { } directly. A guide that creates iosMain by hand with create("iosMain") { dependsOn(...) } is not only longer: it disables the template, and the plugin flags it with a warning. Fourth: the desktop uses OkHttp because Ktor supports it on the JVM, whereas on iOS you need Darwin; without an engine, the HTTP client does not start.
With Android Gradle Plugin 9
The official documentation warns that, from AGP version 9, the Kotlin Multiplatform plugin stops being compatible with com.android.library and com.android.application applied to a multiplatform module. The shared module moves to the com.android.kotlin.multiplatform.library plugin, and the androidTarget { } block becomes androidLibrary { }; the Android app, which could previously live in the same module, goes into a separate module.
// shared/build.gradle.kts - schema to adapt, not executed (AGP 9)
plugins {
alias(libs.plugins.kotlin.multiplatform)
alias(libs.plugins.androidMultiplatformLibrary) // id "com.android.kotlin.multiplatform.library"
}
kotlin {
androidLibrary {
namespace = "com.example.mykmpapp.shared"
compileSdk = 35
compilerOptions { jvmTarget.set(JvmTarget.JVM_17) }
}
// the other targets and the sourceSets stay as seen above
}
The reason to choose right away is that the migration is not a version change but a change of structure: if you create the project with AGP 8 today and update later, you will have to extract the app from the shared module. If you start from zero and can use AGP 9, adopt the new plugin directly. The other blocks in this article remain valid in both cases, except the android { } line, which in AGP 9 disappears in favour of androidLibrary { }.
Step 4: reading the source set hierarchy
A source set is a folder of sources with its own dependencies, and the arrow of the hierarchy goes from the platform towards the common code: iosMain sees everything that commonMain sees, plus the iOS APIs. The compiler forbids the opposite, and that is what protects you from calling android.os.Build by mistake in code that has to run on iOS.
commonMain
├── androidMain
├── desktopMain
└── nativeMain
└── appleMain
└── iosMain
├── iosArm64Main # real iPhone
└── iosSimulatorArm64Main # simulator on Apple Silicon
Note the reading direction: each node inherits from the one above. This explains a curious case that the documentation points out: the native source set, despite its name, in this project has access to the full iOS APIs, because the only native targets you declared are iOS. The documentation warns that this behaviour could change, and that by adding a non-Apple native target nativeMain could no longer use those APIs: do not write code that uses UIKit in nativeMain.
Step 5: your first expect/actual function
When the common code needs something that depends on the platform, you declare a function with expect in commonMain and implement it with actual in every platform source set, with the same name and in the same package. The compiler checks that every expect has an actual for every target. We use the model suggested by the documentation: a common interface and an expect factory function.
// commonMain/kotlin/com/example/mykmpapp/Platform.kt
interface Platform {
val name: String
}
expect fun getPlatform(): Platform
class Greeting {
fun greet(): String = "Hello from ${getPlatform().name}!"
}
// androidMain/kotlin/com/example/mykmpapp/Platform.android.kt
import android.os.Build
class AndroidPlatform : Platform {
override val name: String = "Android ${Build.VERSION.SDK_INT}"
}
actual fun getPlatform(): Platform = AndroidPlatform()
// iosMain/kotlin/com/example/mykmpapp/Platform.ios.kt
import platform.UIKit.UIDevice
class IOSPlatform : Platform {
override val name: String =
UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
}
actual fun getPlatform(): Platform = IOSPlatform()
The three sections live in different files, gathered here for readability. The design point is that expect sits on a function that returns an interface, not on a class: the same advice the official documentation gives, because with the interface you can replace the implementation in a test with a fake, and you can have more than one implementation on the same platform. expect classes exist but they are in Beta, and to use them you need to add a compiler option.
// shared/build.gradle.kts - only if you use expect/actual classes
kotlin {
compilerOptions {
freeCompilerArgs.add("-Xexpect-actual-classes")
}
}
Without this line the compiler warns that you are using a Beta feature; with the line the warning disappears, but the Beta remains. Before writing an expect, ask yourself whether the standard library or kotlinx already offers the function you are looking for (the current time, for example, is in kotlinx-datetime), because every expect you write is code you maintain in two or three copies.
Step 6: the Android app
The Android app is an ordinary Gradle module that depends on shared. To reference it I use project(":shared"), which works without enabling experimental Gradle features.
// androidApp/build.gradle.kts - schema to adapt, not executed
plugins {
alias(libs.plugins.android.application)
}
android {
namespace = "com.example.mykmpapp.android"
compileSdk = 35
defaultConfig {
applicationId = "com.example.mykmpapp"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "1.0"
}
}
dependencies {
implementation(project(":shared"))
}
The file is short on purpose: the only line that connects the two worlds is implementation(project(":shared")). You add the UI dependencies (Compose, View) yourself, depending on how you build the interface. If you forget to include :shared in settings.gradle.kts with include(":shared", ":androidApp"), Gradle cannot find the project and the error message points to a nonexistent module.
Step 7: the iOS app
The shared module becomes a framework that Xcode imports. The link is made with a Run Script in Xcode's Build Phases that calls the Gradle task embedAndSignAppleFrameworkForXcode, designed precisely to be launched from Xcode. The generator already sets it up: you only have to not remove it and, if you change the module name, update it.
# Xcode: Build Phases, Run Script - schema to adapt, not executed
cd "$SRCROOT/.."
./gradlew :shared:embedAndSignAppleFrameworkForXcode
If the task does not run, the typical error is that Xcode imports an old or missing framework: clean the Xcode build and check that the script phase comes before the phase that compiles the Swift sources. After compilation, the framework is imported with the name set in baseName and the Greeting class is used like any Swift class.
// iosApp/ContentView.swift - schema to adapt, not executed
import SwiftUI
import Shared // baseName of the framework
struct ContentView: View {
var body: some View {
Text(Greeting().greet())
.padding()
}
}
Here you see the fruit of the previous steps: Greeting().greet() is Kotlin code compiled for iOS, called from SwiftUI. If you wanted to expose a suspend function on greet, you would see it in Swift as a function with a callback, unless you use Swift export, which is in Alpha (the first article of the series covers it).
Verifying with a shared test
The most useful test at this stage does not probe the platform, but confirms that the expect → actual chain is complete: if an actual is missing for a target, the test does not compile for that target.
// commonTest/kotlin/com/example/mykmpapp/GreetingTest.kt
import kotlin.test.Test
import kotlin.test.assertTrue
class GreetingTest {
@Test
fun greetingMentionsThePlatform() {
assertTrue(Greeting().greet().startsWith("Hello from"))
}
}
// Terminal, schema to adapt, not executed:
// ./gradlew :shared:desktopTest
// ./gradlew :shared:iosSimulatorArm64Test (macOS only)
The task name follows the target name: having written jvm("desktop"), the task is desktopTest, not jvmTest. The JVM is the fastest target, so it is the one to use in most tests; you reserve the iOS target for checks that really require Apple's APIs. The test was not run, so I report no result.
When something does not work
The errors of a first KMP project almost always fall into four categories, each with a recognisable cause.
- An
expectwithout anactual: the implementation is missing for one of the declared targets; the compiler flags it with the name of the declaration and of the target. - A warning about the hierarchy template not being applied: you wrote a
dependsOnby hand; remove it or disable the template. - A library that compiles on Android but not on iOS: it does not declare the iOS target, and must be replaced with a multiplatform library.
- Xcode showing old code: the framework was not rebuilt before the Swift compilation.
The common thread is that errors come from the boundary between two worlds, never from the common code itself. When a build fails, therefore, start from the target that fails and not from the module: :shared:compileKotlinIosSimulatorArm64 tells you where to look, whereas the final Gradle message often does not.
What you can do now
You can read a generated KMP project and find its parts: catalog, targets, source sets, apps. You can tell the AGP 8 configuration from the AGP 9 one, avoid the manual dependsOn thanks to the hierarchy template, write an expect as a function that returns an interface, and connect the framework to Xcode. The next step is to decide where the platform infrastructure goes and how to inject it: you find it in Shared Module Architecture. If you are interested in the comparison with Flutter's way of talking to native code, read Platform Channels: Swift and Kotlin.
Sources
- Hierarchical project structure (kotlinlang.org) - default hierarchy template, warning on manual
dependsOn; consulted on 2026-11-12. - Expected and actual declarations (kotlinlang.org) - expect/actual rules, Beta classes and the
-Xexpect-actual-classesoption; consulted on 2026-11-12. - Use platform-specific APIs (kotlinlang.org) - common interface + expect function model, example with
UIDevice; consulted on 2026-11-12. - Updating multiplatform projects with Android apps to use AGP 9 (kotlinlang.org) -
com.android.kotlin.multiplatform.libraryplugin andandroidLibraryblock; consulted on 2026-11-12. - Ktor client engines (ktor.io) - OkHttp (JVM and Android) and Darwin (iOS) engines; consulted on 2026-11-12.
- Maven Central,
curl -s -o /dev/null -w "%{http_code}" https://repo.maven.apache.org/maven2/<group>/<artifact>/<version>/- response 200 for the catalog versions (Ktor 2.3.12, Koin 3.5.6, SQLDelight 2.0.2, coroutines 1.9.0, serialization 1.7.3, datetime 0.6.1, Kotlin 2.0.20); AGP 8.6.1 on the Google repository; measured on 2026-11-12.
Commenti
Caricamento commenti...
Sign in to comment