expect/actual and source sets
Why it matters
- Every Kotlin Multiplatform project hits the question 'where does platform-specific code go?' Source sets and
expect/actualdeclarations are the answer, and interviewers probe whether you know the boundary between them. - A missing
actualfor a newly added target (e.g.iosSimulatorArm64()) is a common KMP build break. Knowing the default hierarchy template prevents it. - Choosing
expect/actualover an interface with DI (for example Koin) changes how you add targets, test in isolation, and swap implementations. Senior interviews test that trade-off. - The
kotlin("multiplatform")Gradle DSL with an Android target,iosArm64(),iosSimulatorArm64()andbinaries.framework { }is where every KMP build starts; you must read it fluently.
The simple explanation
In Kotlin Multiplatform, expect declares an API in commonMain without an implementation, and each platform source set (androidMain, iosMain) provides the matching actual implementation. The compiler checks that every target has one. Source sets are the folders of code compiled for a set of targets: commonMain for all of them, androidMain for Android, iosMain for all iOS targets.
- A restaurant menu (
commonMain) promises a dish by name: "house bread" (expect fun). - Each kitchen (
androidMain,iosMain) must actually bake it with local ingredients (actual fun). - If a new location opens (a new target) and its kitchen cannot make the dish, the menu cannot be printed: the build fails.
- For a whole service, such as delivery, the menu just says "delivery partner" (an interface) and each location signs its own contract (DI).
The Kotlin Multiplatform Gradle plugin kotlin("multiplatform") creates a source set per target. commonMain is shared by every target; androidMain belongs to the Android target; and the default hierarchy template (Kotlin 1.9.20+) adds intermediate source sets such as nativeMain, appleMain and iosMain. iosMain is the parent of iosArm64Main and iosSimulatorArm64Main (plus iosX64Main if you declare the Intel-simulator target).
expect declares a contract in commonMain; each platform source set supplies the matching actual, in the same package. A target without an actual is a compile error, not a runtime crash.
| Source set | Covers |
|---|---|
commonMain | all targets |
androidMain | the Android target |
iosMain | all declared iOS targets |
iosArm64Main | iOS devices only |
expect/actual functions and properties are stable. expect/actual classes are Beta: the compiler warns, and you silence it with the -Xexpect-actual-classes compiler option. The Kotlin docs recommend standard constructs wherever possible, so for most platform logic (repositories, storage, networking) prefer an interface in commonMain with implementations in androidMain / iosMain, injected with Koin or plain constructor injection (Hilt is Android-only). Keep expect/actual for small primitives such as a platform name, a UUID or a logger function.
The iOS targets produce a .framework when you declare binaries.framework { } on them. Swift sees that framework through a generated Objective-C header; suspend functions appear as completion handlers (callable with async), and Flow needs a wrapper (SKIE or KMP-NativeCoroutines) for idiomatic Swift use. Direct Swift export is still experimental.
Notes
expect/actualfunctions and properties are stable;expect/actualclasses are Beta and produce a warning unless you add the-Xexpect-actual-classescompiler option. Avoid them unless an interface really cannot do the job.- The default hierarchy template (Kotlin 1.9.20+) creates intermediate source sets like
iosMain,appleMainandnativeMainfor you. Before it, you creatediosMainyourself and wired each iOS source set to it withdependsOn. - If you add your own
dependsOncalls, the template is no longer applied automatically; callapplyDefaultHierarchyTemplate()explicitly when you only want to add an extra group. - For most platform-specific logic, define an interface in
commonMainand inject the implementation with Koin or constructor injection. Useexpect/actualfor true primitives (platform name, UUID, a time source). - Each
actualmust be in the same package as itsexpectand match its signature: name, parameter types and return type. A mismatch such asString?versusStringis a compile error. - Name platform files with a suffix, such as
Platform.kt,Platform.android.ktandPlatform.ios.kt, so files for different source sets do not clash on the JVM. - Adding a new target without an
actualthat covers it is a compile error. Put iOSactualdeclarations iniosMain, so one declaration covers every iOS target. - The Gradle DSL declares targets (
android { }with the Android-KMP library plugin, orandroidTarget()in older setups, plusiosArm64()andiosSimulatorArm64()) andbinaries.framework { }to produce the iOS.framework. - Hilt is Android-only and cannot be used in
commonMainoriosMain; Koin is the most common KMP DI library. - Ktor client uses the OkHttp engine on Android and the Darwin engine on iOS; kotlinx.serialization and kotlinx.coroutines work in
commonMain. - Swift interop: Kotlin/Native exports an Objective-C header.
suspendfunctions become completion handlers, callable withasyncin Swift.Flowneeds a wrapper (SKIE or KMP-NativeCoroutines). Swift export is experimental.
Code example
This shows the two patterns side by side: expect/actual for small platform primitives, and an interface with one implementation per platform for storage. Each block is a separate file in its source set.
// ---- commonMain/kotlin/com/example/Platform.kt ----
package com.example
// expect/actual for small platform primitives
expect fun platformName(): String
expect fun randomUuid(): String
// an interface for anything bigger: implemented per platform, injected with DI
interface KeyValueStorage {
fun save(key: String, value: String)
fun load(key: String): String?
}
// ---- androidMain/kotlin/com/example/Platform.android.kt ----
package com.example
import android.content.Context
import android.os.Build
import java.util.UUID
actual fun platformName(): String = "Android ${Build.VERSION.SDK_INT}"
actual fun randomUuid(): String = UUID.randomUUID().toString()
class AndroidKeyValueStorage(context: Context) : KeyValueStorage {
private val prefs = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
override fun save(key: String, value: String) {
prefs.edit().putString(key, value).apply()
}
override fun load(key: String): String? = prefs.getString(key, null)
}
// ---- iosMain/kotlin/com/example/Platform.ios.kt ----
package com.example
import platform.Foundation.NSUUID
import platform.Foundation.NSUserDefaults
import platform.UIKit.UIDevice
actual fun platformName(): String =
UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
actual fun randomUuid(): String = NSUUID().UUIDString()
class IosKeyValueStorage : KeyValueStorage {
private val defaults = NSUserDefaults.standardUserDefaults
override fun save(key: String, value: String) {
defaults.setObject(value, forKey = key)
}
override fun load(key: String): String? = defaults.stringForKey(key)
}expect/actualis used only for two primitives.KeyValueStorageis an interface, not anexpectclass, so each platform's Koin module can bind its implementation andcommonTestcan use an in-memory fake.- Each
actualis in the same package as itsexpect. The.android.ktand.ios.ktfile suffixes keep the generated JVM class names from clashing withPlatform.ktincommonMain. AndroidKeyValueStorageneeds aContext, which only exists on Android. That is exactly why it is a class behind an interface rather than anexpect fun: the Android Koin module can pass it the application context.
Run the idea in plain Kotlin
interface PlatformInfo {
fun name(): String
fun cacheDir(): String
}
class AndroidPlatformInfo : PlatformInfo {
override fun name(): String = "Android"
override fun cacheDir(): String = "/data/data/com.example/cache"
}
class IosPlatformInfo : PlatformInfo {
override fun name(): String = "iOS"
override fun cacheDir(): String = "/var/mobile/Containers/Data/Application/cache"
}
fun main() {
val platforms: List<PlatformInfo> = listOf(AndroidPlatformInfo(), IosPlatformInfo())
for (p in platforms) {
println("Platform: " + p.name() + " Cache: " + p.cacheDir())
}
println("---")
println("expect fun in commonMain: one actual per target, checked at compile time")
println("A target without an actual fails the build")
println("Bigger abstractions: an interface in commonMain, injected with DI")
}Expected output:
Platform: Android Cache: /data/data/com.example/cache
Platform: iOS Cache: /var/mobile/Containers/Data/Application/cache
---
expect fun in commonMain: one actual per target, checked at compile time
A target without an actual fails the build
Bigger abstractions: an interface in commonMain, injected with DI
- The Playground runs on one JVM, so it models each target's
actualas an interface implementation chosen at runtime. In a real KMP build each target is compiled separately and contains only its ownactual. The paths are illustrative, not real directories.
In production
- A team added
iosSimulatorArm64()to the Gradle block so developers on Apple silicon Macs could use the simulator. - Every simulator build failed with errors that
expectdeclarations had noactualfor the new target. - Root cause: an old hand-written setup kept
actualimplementations separately iniosX64MainandiosArm64Main, not in a sharediosMainparent.
- Removed the hand-written
dependsOnwiring so the default hierarchy template applied (Kotlin 1.9.20+). - Moved the iOS
actualdeclarations from the leaf source sets intoiosMain, deleting the duplicates. - Added a CI job on a macOS runner that compiles every target, so a missing
actualis caught before merge.
- A repository was declared as
expect class UserRepositoryincommonMain, with anactual classinandroidMainand iniosMain. - Shared tests in
commonTestcould not swap in a fake, because there is exactly oneactualper target and tests got the real platform implementation with real storage. - Every new method had to be added to the
expectand to eachactual, and the Beta warning forexpect/actualclasses showed up in every build.
- Replaced the
expect/actualclass with an interfaceUserRepositoryincommonMain. - Implemented
AndroidUserRepositoryandIosUserRepositoryin their platform source sets and registered them in platform Koin modules. - Shared tests now pass a
FakeUserRepository; theexpect/actualclass was deleted.
Common mistakes
- Using an expect/actual class for a repository or use case.
expect/actualclasses are Beta, allow only one implementation per target, and make fakes incommonTestawkward. Use an interface incommonMainwith DI instead. - Forgetting an actual when adding a new target. Adding
iosSimulatorArm64()without anactualiniosMain(or the new leaf source set) is a compile error for that target. Always run a full multi-target build after adding a target. - Putting platform-specific code in commonMain.
commonMaincannot seeandroid.*,platform.Foundationorjava.*APIs, so such code does not compile there. Move it to a platform source set behind an interface or anexpectdeclaration. - Mismatched expect/actual signatures. The
actualmust match theexpectname, parameter types and return type, and live in the same package. AString?versusStringmismatch is a compile error, not a warning. - Hand-wiring source sets the template already creates. Old guides tell you to create
iosMainand adddependsOncalls by hand. On Kotlin 1.9.20+ that switches off the default hierarchy template and is easy to get wrong; rely on the template and only add extra groups when needed. - Using Hilt in commonMain. Hilt is Android-only and depends on AndroidX. In KMP, use Koin or constructor injection so the DI graph for shared code works on iOS too.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is expect/actual and when would you use it?”
“How do KMP source sets work?”
“expect/actual versus interface plus DI: which do you choose and why?”
“What happens when you add a new target like iosSimulatorArm64()?”
Quiz
Which source set is the direct parent of iosArm64Main and iosSimulatorArm64Main under the default hierarchy template?
What is the current status of expect/actual classes in Kotlin?
Which DI library works across all KMP targets including iOS?
A team adds iosSimulatorArm64() and the simulator build fails because expect declarations have no actual. What is the most likely cause?
0 of 4 answered
Mini task
15-minute exercise: expect/actual and source sets
You need a Mac with Xcode to build the iOS targets.
-
Create a KMP module. Apply
kotlin("multiplatform")and the Android-KMP library plugin (com.android.kotlin.multiplatform.library), configureandroid { }insidekotlin { }, and declareiosArm64()andiosSimulatorArm64(), each withbinaries.framework { baseName = "Shared" }. -
Add expect primitives. In
commonMaindeclareexpect fun platformName(): Stringandexpect fun randomUuid(): String. -
Provide actuals. In
androidMainuseBuild.VERSION.SDK_INTandUUID.randomUUID().toString(). IniosMainuseUIDevice.currentDeviceandNSUUID().UUIDString(). Name the filesPlatform.android.ktandPlatform.ios.kt. -
Add an interface. In
commonMaindeclare aKeyValueStorageinterface withsave(key, value)andload(key). Implement it inandroidMainwithSharedPreferencesand iniosMainwithNSUserDefaults. -
Break it on purpose. Move the iOS actuals from
iosMainintoiosArm64Mainand build. Read the missing-actual error foriosSimulatorArm64, then move them back toiosMain. -
Verify commonMain is clean. Search
commonMainforandroid.,platform.orjava.imports. There should be none.
Done condition: ./gradlew :shared:build succeeds, commonMain has no platform imports, and ./gradlew :shared:linkDebugFrameworkIosSimulatorArm64 produces Shared.framework under shared/build/bin/iosSimulatorArm64/debugFramework/.