# Kotlin's expect/actual: A Compile-Time Interface, Not a Runtime One

> expect/actual looks like an interface with per-platform implementations, but there's no dispatch, no vtable, and no single binary containing more than one actual. The compiler swaps it in per target, at compile time.

**Date:** 2026-10-29T00:00:00.000Z
**Tags:** Multiplatform, Compiler

## What `expect`/`actual` actually is

`expect`/`actual` is Kotlin Multiplatform's mechanism for writing one
declaration in shared code and giving it a different body per platform.

* An **`expect`** declaration lives in `commonMain`. It declares a
  class, function, or property's signature with no body, a promise that
  a matching implementation exists for every platform the project builds.
* An **`actual`** declaration lives in a platform
  source set (A directory of code scoped to one platform (or a group of platforms), like androidMain or iosMain, compiled only into that platform's build. commonMain is itself a source set, just one every platform shares.),
  such as `androidMain` or `iosMain`, and fulfills that promise with the
  real implementation for that one platform.
* The compiler checks that every `expect` has a matching `actual` for
  each target being built, and fails the build if one's missing.

That's the contract. What it doesn't tell you is *when* the matching
happens, and that's where the mental model usually goes wrong.

## The intuition

`expect`/`actual` reads like an interface with per-platform
implementations: define an interface, inject a different implementation
on Android vs. iOS. That picture carries over naturally from dependency
injection. It's wrong in a specific way.

* An interface has exactly one compiled form, and *which* implementation
  runs is decided at
  runtime (Not when the code is written, which is still compile time, every override already exists in the binary. Runtime here means dispatch: a vtable lookup picks which of the already-compiled implementations to jump to for this specific call, based on the object's actual class.),
  by whatever the DI graph (or a plain `if`) hands you.
* An `expect` declaration has no compiled form of its own at all. Every
  target compiles commonMain against its own matching `actual`, baked in,
  before the binary exists.
* There's never a moment where both the Android `actual` and the iOS
  `actual` exist in the same compiled artifact. Each target's build only
  ever sees one of them, the one that's `actual` for it.

So "swap the implementation" happens at compile time, per source set, not
at runtime inside a running process. There's nothing to swap once a
binary exists, because nothing else was ever compiled into it.

## A platform logger, the obvious way

```kotlin
// commonMain
expect class PlatformLogger() {
    fun log(message: String)
}

fun greet() {
    PlatformLogger().log("Hello from commonMain")
}
```

```kotlin
// androidMain
actual class PlatformLogger {
    actual fun log(message: String) {
        android.util.Log.d("App", message)
    }
}
```

```kotlin
// iosMain
actual class PlatformLogger {
    actual fun log(message: String) {
        platform.Foundation.NSLog(message)
    }
}
```

`greet()` is written once in commonMain and calls `PlatformLogger().log(...)`
without knowing which platform it'll run on. That part does look like
calling through an interface.

The difference shows up in what the Android build actually compiles:

* It never sees `iosMain`'s `actual class PlatformLogger` at all, not as
  dead code, not as an unused branch, not compiled anywhere.
* The Android compilation unit is `commonMain` + `androidMain` only, with
  every `expect` in it resolved directly to its `androidMain` `actual`
  before code generation happens.

Swap `androidMain` for `iosMain` and you get a *different, separately
compiled* binary, not a different runtime path through the same one.

```mermaid caption="Each target's compilation only ever pulls in commonMain plus its own actual; the Android binary never contains the iOS actual, and vice versa" figureNumber={1}
flowchart TD
    Common["commonMain<br/>expect class PlatformLogger"]
    AndroidActual["androidMain<br/>actual: Log.d(...)"]
    IosActual["iosMain<br/>actual: NSLog(...)"]
    AndroidBuild["Android compilation<br/>commonMain + androidMain only"]
    IosBuild["iOS compilation<br/>commonMain + iosMain only"]
    AndroidBinary["Android binary<br/>only the Android actual exists here"]
    IosBinary["iOS binary<br/>only the iOS actual exists here"]

    Common --> AndroidBuild
    Common --> IosBuild
    AndroidActual --> AndroidBuild
    IosActual --> IosBuild
    AndroidBuild --> AndroidBinary
    IosBuild --> IosBinary
```

## Trying to pick an actual at runtime doesn't typecheck

```kotlin
// ❌ there's no PlatformLogger "interface" to hold a reference to;
// expect declarations aren't a type you can swap behind a variable
class Container(private val logger: PlatformLogger)

fun buildForTesting(): Container {
    // trying to inject a fake implementation the way you would for
    // a real interface
    return Container(logger = FakePlatformLogger()) // compile error:
    // FakePlatformLogger isn't a subtype of PlatformLogger: classes are
    // final by default in Kotlin, and this expect/actual pair doesn't
    // mark itself open
}
```

This is the mistake the DI mental model leads straight to: reaching for
`expect`/`actual` to get a fake/swappable implementation for tests, the
same way you'd swap a `Repository` interface for a `FakeRepository`.
`PlatformLogger` can't be subclassed here, but that's ordinary Kotlin
behavior (classes are final unless marked `open`), not something
`expect`/`actual` invents. Marking it `expect open class PlatformLogger()`
wouldn't rescue the DI use case either: it would let you subclass
whichever one `actual` class made it into that target's binary, not
swap between Android's and a fake's at the same call site. Open or not,
you still only ever get one `PlatformLogger` type per compilation.

If you want a runtime-swappable implementation (for tests, feature flags,
or anything else decided while the program is running), you still need
an actual Kotlin `interface`. `expect`/`actual` only comes back in to
provide the platform-specific *construction* of one implementation, if
that's needed.

```kotlin
// commonMain — a real interface, no expect/actual needed, since it has
// no platform-specific body to fill in
interface Logger {
    fun log(message: String)
}

class Container(private val logger: Logger)
```

```kotlin
// androidMain — an ordinary class implementing the interface
class AndroidLogger : Logger {
    override fun log(message: String) = android.util.Log.d("App", message)
}
```

```kotlin
// commonTest — FakePlatformLogger failed to typecheck earlier because
// PlatformLogger is final; FakeLogger works because Logger is
class FakeLogger : Logger {
    val messages = mutableListOf<String>()
    override fun log(message: String) { messages += message }
}

fun buildForTesting(): Container = Container(logger = FakeLogger())
```

`expect`/`actual` still earns its place here, just one level over: picking
*which* implementation gets constructed per platform, not standing in for
the interface itself.

```kotlin
// commonMain
expect fun providePlatformLogger(): Logger

// androidMain
actual fun providePlatformLogger(): Logger = AndroidLogger()

// iosMain
actual fun providePlatformLogger(): Logger = IosLogger()
```

## Real-world use cases

`PlatformLogger` is deliberately minimal. In production KMP codebases,
`expect`/`actual` tends to show up at the same handful of seams, wherever
shared logic needs exactly one platform primitive to get started from.

### Unique identifiers

```kotlin
// commonMain
expect fun randomUuid(): String

// androidMain
actual fun randomUuid(): String = java.util.UUID.randomUUID().toString()

// iosMain
actual fun randomUuid(): String = platform.Foundation.NSUUID().UUIDString
```

Both platforms already ship a UUID generator. `expect`/`actual` just gives
shared code one name to call, instead of branching on the platform inside
commonMain to pick between two platform-specific ones.

### Reading platform info for diagnostics

```kotlin
// commonMain
expect fun platformName(): String

// androidMain
actual fun platformName(): String = "Android ${android.os.Build.VERSION.SDK_INT}"

// iosMain
actual fun platformName(): String =
    platform.UIKit.UIDevice.currentDevice.let { "${it.systemName} ${it.systemVersion}" }
```

This one ships in the default Kotlin Multiplatform project template,
usually read into crash reports or analytics events that need to know
which OS they came from.

### Base64 encoding

```kotlin
// commonMain
expect fun String.encodeBase64(): String

// androidMain
actual fun String.encodeBase64(): String =
    android.util.Base64.encodeToString(encodeToByteArray(), android.util.Base64.NO_WRAP)

// iosMain
actual fun String.encodeBase64(): String =
    (this as platform.Foundation.NSString)
        .dataUsingEncoding(platform.Foundation.NSUTF8StringEncoding)!!
        .base64EncodedStringWithOptions(0u)
```

Both platforms already have a Base64 encoder sitting in their standard
library. `expect`/`actual` just gives shared serialization code one
extension function to call instead of branching between two.

### Wall-clock time

```kotlin
// commonMain
expect fun currentTimeMillis(): Long

// androidMain
actual fun currentTimeMillis(): Long = System.currentTimeMillis()

// iosMain
actual fun currentTimeMillis(): Long =
    (platform.Foundation.NSDate().timeIntervalSince1970 * 1000).toLong()
```

This is the textbook `expect`/`actual` example. It still shows up in
codebases that haven't pulled in `kotlinx-datetime`'s `Clock.System.now()`
yet, which solves the exact same problem as a portable library instead
of a project-local `expect`/`actual`. Same shape as UUID generation: a
stdlib primitive that exists on every platform under a different name,
unified under one commonMain signature.

UUIDs, platform info, Base64, and wall-clock time all follow the same
shape: one signature in commonMain, one body per platform, resolved
before either binary exists, because none of them needs extra
constructor arguments on just one side.

### When not to use expect/actual: secure credential storage

Shared login/session code needs to persist a token, but *how* it's stored
securely is inherently platform-specific. Android's answer needs a
`Context` to get there, and that breaks the shape every example above
relied on.

`expect`/`actual` can't thread a `Context` through cleanly: every
`actual` constructor has to match the `expect`'s exactly, args and all,
so an Android-only parameter has nowhere to go. The same interface
pattern from the Logger example earlier sidesteps the problem instead of
working around it:

```kotlin
// commonMain — a plain interface, same shape as Logger: no constructor
// to keep in sync across platforms, so no expect/actual needed at all
interface SecureStorage {
    fun save(key: String, value: String)
    fun read(key: String): String?
}
```

```kotlin
// androidMain — constructed with Context, which this platform's DI
// module has on hand; backed by EncryptedSharedPreferences
class AndroidSecureStorage(private val context: Context) : SecureStorage {
    private val prefs = EncryptedSharedPreferences.create(context, /* ... */)
    override fun save(key: String, value: String) = prefs.edit().putString(key, value).apply()
    override fun read(key: String): String? = prefs.getString(key, null)
}
```

```kotlin
// iosMain — no Context to thread through, so nothing to work around;
// backed by the Keychain
class IosSecureStorage : SecureStorage {
    override fun save(key: String, value: String) { /* SecItemAdd(...) */ }
    override fun read(key: String): String? = /* SecItemCopyMatching(...) */ null
}
```

Each platform's DI module (Koin, Kodein, hand-rolled) binds
`SecureStorage` to its own constructor call: `AndroidSecureStorage(context)`
on Android, `IosSecureStorage()` on iOS. The shared `AuthRepository` just
calls `save(...)` on whatever `SecureStorage` its DI graph handed it,
never knowing which backing store that was. Neither platform's
constructor is ever constrained by the other's.

`SecureStorage` is the tell for when `expect`/`actual`'s shape stops
fitting: the moment one platform's implementation needs something (a
`Context`, a handle, anything) the other platform doesn't, reach for the
interface instead of forcing it through `expect`/`actual`.

> **The fundamental**
>
> This is **compile-time polymorphism**: resolving which implementation a
> call site uses as part of compilation, by literally substituting the
> right declaration into the right source set.
>
> That's different from **runtime (dynamic) polymorphism**, where one
> compiled call site stays ambiguous until a vtable (A table of function-pointer slots attached to a compiled class, one per overridable method. A virtual call looks up the right function through this table at runtime instead of jumping to a fixed address, which is how one call site can reach a different override depending on the object's actual class.) lookup
> (or a DI container) picks a concrete implementation while the program is
> running.
>
> `expect`/`actual` has zero runtime cost and zero runtime flexibility by
> design: there's exactly one `actual` per `expect` per compilation, chosen
> before the binary exists.
>
> That's also why you can't have two actuals available in the same running
> process the way you can have two classes implementing the same
> interface.

## Elsewhere: same fundamental, different framework

* **C/C++ preprocessor**: `#ifdef _WIN32 ... #else ... #endif` is resolved
  by the preprocessor before the compiler proper ever runs, textually
  substituting one branch and deleting the other. Same "only one version
  ever gets compiled" guarantee, just at the text level instead of the
  declaration level.
* **Rust's `#[cfg(...)]`**: `#[cfg(target_os = "ios")] fn platform_name()
  -> &'static str { "iOS" }` alongside an Android version with the same
  signature is resolved by the compiler per build target. Only the
  matching `cfg` block is ever compiled in; the others don't exist in
  that binary, not even as unreachable code.
* **Swift's `#if os(iOS)` / `#if canImport(...)`**: compiler directives
  that keep or drop a block per target before type-checking happens, the
  same per-platform-source-file pattern KMP's `iosMain`/`androidMain`
  split mirrors. A Swift Package Manager target that links a KMP
  framework is, underneath, doing the same "only one version of this
  symbol was ever compiled" trick on its own side of the boundary.
* **Java's multi-release JARs** (`META-INF/versions/`) look similar but
  aren't: the JVM picks a class file version at *class-load time*, based
  on the running JVM's version, so a single JAR genuinely does ship
  multiple compiled versions and defers the choice to runtime. That's the
  dynamic-polymorphism shape `expect`/`actual` deliberately avoids.

## Edge cases

### Adding a target later surfaces the missing `actual` as a build error, not a test failure

```text
e: Expected class 'PlatformLogger' has no actual declaration in module
<app-wasmJsMain> for target WASM
```

If a new target is added to the project (say, `wasmJsMain`) and nobody
writes a matching `actual`, the failure is a compile error on that
target's build, not a runtime crash and not a unit test failure.

It's easy to miss if CI doesn't actually build every target, since the
`expect` declaration itself compiles fine in commonMain regardless of how
many `actual`s exist for it.

### An `actual` can't expose extra public API the `expect` didn't declare

```kotlin
// commonMain
expect class PlatformLogger() {
    fun log(message: String)
}

// androidMain
actual class PlatformLogger {
    actual fun log(message: String) { /* ... */ }
    fun logWithTag(tag: String, message: String) { /* ... */ } // compiles fine here
}

// commonMain, calling code
PlatformLogger().logWithTag("App", "hi") // unresolved reference
```

`logWithTag` compiles because `androidMain` is a real class and can have
whatever members it wants. It's just invisible from `commonMain`, since
commonMain only ever sees the shape `expect` promised, not whatever a
particular `actual` happens to add.

This is the opposite failure from the missing-actual case above: the code
compiles everywhere, it just doesn't do what you expected from the call
site you wrote it at.

### `actual typealias` skips a class body entirely, and the match still has to be exact

```kotlin
// commonMain
expect class PlatformDate

// jvmMain, aliasing straight to an existing platform type instead of
// writing a wrapper class
actual typealias PlatformDate = java.time.LocalDate
```

No `actual class` body at all here, `java.time.LocalDate` just *is* the
`actual`. This is the usual move when the platform already has the right
type and wrapping it would be pure ceremony. It's still resolved the same
way, at compile time, per target. The typealias is just a shorter path
to the same substitution.

**`expect`/`actual` is compile-time substitution, not dispatch: the compiler
picks one `actual` per target before the binary exists, so there's never
a running process holding more than one implementation to choose
between.**


---

Canonical page: https://recomposed.blog/kotlin-expect-actual