expect/actual and source sets

Learn Kotlin Multiplatform expect/actual declarations and source sets (commonMain, androidMain, iosMain), and when interfaces plus DI are the better choice. About 25 minutes.

Why it matters

  • Every Kotlin Multiplatform project hits the question 'where does platform-specific code go?' Source sets and expect/actual declarations are the answer, and interviewers probe whether you know the boundary between them.
  • A missing actual for a newly added target (e.g. iosSimulatorArm64()) is a common KMP build break. Knowing the default hierarchy template prevents it.
  • Choosing expect/actual over 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() and binaries.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 setCovers
commonMainall targets
androidMainthe Android target
iosMainall declared iOS targets
iosArm64MainiOS 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.

Shared code at the top, platform code below
Kotlin Multiplatform source sets commonMain declares an expect function and is shared by every target; androidMain and iosMain each provide the actual implementation, and iosMain is the parent of the iosArm64Main and iosSimulatorArm64Main source sets. commonMain expect fun platformName() androidMain actual fun platformName() iosMain actual fun platformName() iosArm64Main iPhone devices iosSimulatorArm64Main simulators on Apple silicon Every target needs an actual. A missing one is a compile error, not a crash.
commonMain promises the API, and each platform source set supplies the actual. The default hierarchy also adds appleMain and nativeMain above iosMain.

Notes

  • expect/actual functions and properties are stable; expect/actual classes are Beta and produce a warning unless you add the -Xexpect-actual-classes compiler 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, appleMain and nativeMain for you. Before it, you created iosMain yourself and wired each iOS source set to it with dependsOn.
  • If you add your own dependsOn calls, the template is no longer applied automatically; call applyDefaultHierarchyTemplate() explicitly when you only want to add an extra group.
  • For most platform-specific logic, define an interface in commonMain and inject the implementation with Koin or constructor injection. Use expect/actual for true primitives (platform name, UUID, a time source).
  • Each actual must be in the same package as its expect and match its signature: name, parameter types and return type. A mismatch such as String? versus String is a compile error.
  • Name platform files with a suffix, such as Platform.kt, Platform.android.kt and Platform.ios.kt, so files for different source sets do not clash on the JVM.
  • Adding a new target without an actual that covers it is a compile error. Put iOS actual declarations in iosMain, so one declaration covers every iOS target.
  • The Gradle DSL declares targets (android { } with the Android-KMP library plugin, or androidTarget() in older setups, plus iosArm64() and iosSimulatorArm64()) and binaries.framework { } to produce the iOS .framework.
  • Hilt is Android-only and cannot be used in commonMain or iosMain; 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. suspend functions become completion handlers, callable with async in Swift. Flow needs 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/actual is used only for two primitives. KeyValueStorage is an interface, not an expect class, so each platform's Koin module can bind its implementation and commonTest can use an in-memory fake.
  • Each actual is in the same package as its expect. The .android.kt and .ios.kt file suffixes keep the generated JVM class names from clashing with Platform.kt in commonMain.
  • AndroidKeyValueStorage needs a Context, which only exists on Android. That is exactly why it is a class behind an interface rather than an expect 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 actual as an interface implementation chosen at runtime. In a real KMP build each target is compiled separately and contains only its own actual. The paths are illustrative, not real directories.

In production

Missing actual after adding iosSimulatorArm64()
  • 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 expect declarations had no actual for the new target.
  • Root cause: an old hand-written setup kept actual implementations separately in iosX64Main and iosArm64Main, not in a shared iosMain parent.
The fix
  • Removed the hand-written dependsOn wiring so the default hierarchy template applied (Kotlin 1.9.20+).
  • Moved the iOS actual declarations from the leaf source sets into iosMain, deleting the duplicates.
  • Added a CI job on a macOS runner that compiles every target, so a missing actual is caught before merge.
expect/actual class made a repository hard to test
  • A repository was declared as expect class UserRepository in commonMain, with an actual class in androidMain and in iosMain.
  • Shared tests in commonTest could not swap in a fake, because there is exactly one actual per target and tests got the real platform implementation with real storage.
  • Every new method had to be added to the expect and to each actual, and the Beta warning for expect/actual classes showed up in every build.
The fix
  • Replaced the expect/actual class with an interface UserRepository in commonMain.
  • Implemented AndroidUserRepository and IosUserRepository in their platform source sets and registered them in platform Koin modules.
  • Shared tests now pass a FakeUserRepository; the expect/actual class was deleted.

Common mistakes

  • Using an expect/actual class for a repository or use case. expect/actual classes are Beta, allow only one implementation per target, and make fakes in commonTest awkward. Use an interface in commonMain with DI instead.
  • Forgetting an actual when adding a new target. Adding iosSimulatorArm64() without an actual in iosMain (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. commonMain cannot see android.*, platform.Foundation or java.* APIs, so such code does not compile there. Move it to a platform source set behind an interface or an expect declaration.
  • Mismatched expect/actual signatures. The actual must match the expect name, parameter types and return type, and live in the same package. A String? versus String mismatch is a compile error, not a warning.
  • Hand-wiring source sets the template already creates. Old guides tell you to create iosMain and add dependsOn calls 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.

  1. Create a KMP module. Apply kotlin("multiplatform") and the Android-KMP library plugin (com.android.kotlin.multiplatform.library), configure android { } inside kotlin { }, and declare iosArm64() and iosSimulatorArm64(), each with binaries.framework { baseName = "Shared" }.

  2. Add expect primitives. In commonMain declare expect fun platformName(): String and expect fun randomUuid(): String.

  3. Provide actuals. In androidMain use Build.VERSION.SDK_INT and UUID.randomUUID().toString(). In iosMain use UIDevice.currentDevice and NSUUID().UUIDString(). Name the files Platform.android.kt and Platform.ios.kt.

  4. Add an interface. In commonMain declare a KeyValueStorage interface with save(key, value) and load(key). Implement it in androidMain with SharedPreferences and in iosMain with NSUserDefaults.

  5. Break it on purpose. Move the iOS actuals from iosMain into iosArm64Main and build. Read the missing-actual error for iosSimulatorArm64, then move them back to iosMain.

  6. Verify commonMain is clean. Search commonMain for android., platform. or java. 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/.

Next: Sharing networking and data layers