Multiplatform and expect/actual

Multiplatform and expect/actual in Kotlin: A manufacturer designs one appliance to sell worldwide.

The Analogy: The International Appliance Design

A manufacturer designs one appliance to sell worldwide. The core of the appliance -- its logic, its casing, its controls -- is designed once, in a master specification. But mains electricity differs by region, so the design cannot hard-wire a single power module. Instead the master spec declares that it expects a power module with fixed mounting points and terminals, and leaves the module itself to be supplied locally. Each regional plant then provides the actual module built for its mains -- one for 120 volts, another for 230 -- each fitting the identical mounting points the spec demands. Kotlin Multiplatform works this way: shared common code declares expect for anything that must vary by platform, and each target provides the actual implementation fitting the same signature.

The payoff is that the appliance's behaviour is designed and tested once, in the common specification, while only the genuinely region-specific part varies. The controls, the safety logic, the timing -- all shared -- are written against the expected module's terminals, not against any one region's wiring. In Kotlin, the bulk of your logic lives in the common source set and is compiled for every target, calling expect declarations wherever it needs something a platform must supply, such as the current time, a random source, or an HTTP client.

The arrangement is enforced. A region that cannot supply a conforming power module cannot ship the appliance at all, and a module that does not fit the mounting points is rejected on the assembly line. Kotlin mirrors this: every target must provide an actual for each expect, and the actual must match the expect signature exactly, or the build fails. The common code, the shared source set, and the per-platform source sets -- one for each target -- are the workshop layout that keeps shared and platform-specific parts cleanly separated.

The failure that produces a region-specific defect is two plants supplying modules that fit the mounting points but behave subtly differently -- one delivering a slightly different voltage or reversed polarity. The appliance's shared logic, written assuming uniform behaviour, then malfunctions only in that region, and because the design was tested against just one plant's module, the fault ships undetected. In Kotlin this is divergent actual implementations: two platforms fulfil the same expect signature but with different behaviour, so shared code produces platform-dependent results that tests run on a single platform never catch. The mirror failure is wiring region-specific parts directly into the master specification -- platform-specific code in the common source set -- which then cannot be built for a region that lacks that part. The discipline is to keep the common contract precise and the platform actuals faithful to it.


Syntax or Core Structure

Common code declares expect; each target supplies an actual with a matching signature. The multiplatform shape is illustrative (it needs multiple compilation targets):

// commonMain
expect fun platformName(): String

fun greeting(): String = "Running on " + platformName()

// jvmMain
actual fun platformName(): String = "JVM"

// jsMain
actual fun platformName(): String = "JS"

The underlying pattern -- shared logic written against an abstraction that each platform fulfils -- is ordinary Kotlin and can be shown deterministically with an interface standing in for the expect/actual pair:

interface Platform {
    fun name(): String
}

class JvmPlatform : Platform {
    override fun name(): String = "JVM"
}

class JsPlatform : Platform {
    override fun name(): String = "JS"
}

fun greeting(p: Platform): String = "Running on " + p.name()

fun main() {
    println(greeting(JvmPlatform()))
    println(greeting(JsPlatform()))
}

Output:

Running on JVM
Running on JS

The greeting function is the common code: written once against the Platform abstraction, unaware of any specific platform. Each concrete class -- JvmPlatform, JsPlatform -- is the actual for its target, supplying the platform-specific name. Running greeting with each produces "Running on JVM" and "Running on JS": the same shared logic, only the injected platform part differs. In real multiplatform code, platformName would be an expect function resolved at compile time to the target's actual, rather than an interface passed at runtime, but the separation of shared logic from platform specifics is identical.


Technical Depth: Source Sets, Matching, and Shared Logic

The source set layout

A multiplatform project organises code into source sets, one common and one per target. The table lists the usual ones.

Source setHoldsCompiled for
commonMainshared code and expect declarationsevery target
jvmMainactual implementations for the JVMJVM
jsMainactual implementations for JSJavaScript
nativeMainactual implementations for nativeNative
commonTestshared testsevery target

Code in commonMain may only use APIs available on every target; anything platform-specific must be an expect resolved by each platform's source set. This is what keeps the shared code genuinely portable.

expect/actual signatures must match

An actual must match its expect in name, parameters, and return type on every target, or the build fails -- the module must fit the mounting points. Because the match is by signature, shared code can call the declaration freely.

Shared logic composes with an injected platform part

Business logic in the common set is written once and reused across platforms, calling into the platform-provided piece only where necessary. Modelled with a deterministic stand-in for a platform ID generator:

interface Uuid {
    fun next(): String
}

class SeqUuid(private var n: Int = 0) : Uuid {
    override fun next(): String = "id-" + (n + 1).also { n = it }
}

fun createRecords(count: Int, uuid: Uuid): List<String> =
    (1..count).map { uuid.next() }

fun main() {
    println(createRecords(3, SeqUuid()))
}

Output:

[id-1, id-2, id-3]

createRecords is common logic: it builds a list of records, delegating ID generation to the Uuid abstraction without knowing how IDs are produced. The SeqUuid stand-in yields "id-1", "id-2", "id-3" deterministically, so three records come out with sequential IDs. On a real platform the Uuid would be an actual backed by the platform's own UUID API, but the shared createRecords code -- the part worth writing once -- is identical everywhere and is exactly what a multiplatform project centralises in commonMain.

A platform-provided value feeding common formatting

Common logic can also compose a small platform-provided value, such as a locale's decimal separator, keeping the formatting rule itself shared:

interface Locale {
    val decimal: Char
}

class UsLocale : Locale {
    override val decimal: Char = '.'
}

class EuLocale : Locale {
    override val decimal: Char = ','
}

fun formatPrice(cents: Int, loc: Locale): String {
    val whole = cents / 100
    val frac = cents % 100
    return whole.toString() + loc.decimal + frac.toString().padStart(2, '0')
}

fun main() {
    println(formatPrice(1250, UsLocale()))
    println(formatPrice(1250, EuLocale()))
}

Output:

12.50
12,50

formatPrice holds the shared formatting rule -- split cents into whole and fractional parts, pad the fraction to two digits -- while the decimal separator comes from the injected Locale. With UsLocale the separator is a dot, giving "12.50"; with EuLocale it is a comma, giving "12,50". The structural logic is written once and only the tiny platform-varying piece is supplied per target, which is the balance a good multiplatform design strikes: maximise the shared rule, minimise and isolate what genuinely differs. Note the risk lurking here too -- if the separator alone varies but the formatting rule were instead reimplemented per platform, the two could drift, which is exactly the divergence the next section examines.


Real World Example: Divergent actual Implementations

A billing library declares an expect rounding function in common code, and each platform provides an actual. The JVM plant implements round-half-up; another target's plant, reaching for a local rounding API, implements round-half-to-even (banker's rounding). Both fit the signature, so the build is green, and the shared invoicing logic calls the function trusting it behaves the same everywhere.

interface Rounder {
    fun round(x: Double): Long
}

// actual on platform A: round half up
class PlatformA : Rounder {
    override fun round(x: Double): Long = kotlin.math.floor(x + 0.5).toLong()
}

// actual on platform B: round half to even (a subtly different contract)
class PlatformB : Rounder {
    override fun round(x: Double): Long {
        val f = kotlin.math.floor(x).toLong()
        val frac = x - f
        return when {
            frac < 0.5 -> f
            frac > 0.5 -> f + 1
            else -> if (f % 2 == 0L) f else f + 1
        }
    }
}

fun main() {
    val a = PlatformA()
    val b = PlatformB()
    println("A rounds 2.5 -> " + a.round(2.5))
    println("B rounds 2.5 -> " + b.round(2.5))
    println("agree on 2.5? " + (a.round(2.5) == b.round(2.5)))
    println("agree on 3.5? " + (a.round(3.5) == b.round(3.5)))
}

Output:

A rounds 2.5 -> 3
B rounds 2.5 -> 2
agree on 2.5? false
agree on 3.5? true

For many inputs the two platforms agree -- both round 3.5 to 4 -- so casual testing on either platform looks fine, and the "agree on 3.5? true" line reflects that. The signatures match, the build passes, and the shared code compiles for both targets without complaint.

The half-way cases expose the split. Platform A rounds 2.5 up to 3, while Platform B rounds 2.5 to the nearest even number, 2. The same invoice computed through the same shared code yields a different total depending on the platform it runs on -- "agree on 2.5? false" -- and for money, that is a real discrepancy that reconciliation will eventually surface as a mismatch between, say, an Android client and a JVM backend.

The genuine design flaw is divergent actual implementations: two platforms satisfy the identical expect signature but honour different behavioural contracts, so shared logic silently produces platform-dependent results. The build system checks the signature, not the semantics, and tests run on a single platform can never catch a disagreement that only appears on another. The fix is to keep behaviour that must be identical in the common source set -- implement the rounding rule once in commonMain rather than delegating to platform APIs that differ -- and, for anything that genuinely must be platform-specific, to pin the contract precisely and run the shared test suite (commonTest) on every target so divergence fails the build. The broader limitation is that expect/actual guarantees signature compatibility but not behavioural equivalence, so every actual that wraps a platform API inherits that API's quirks, and uniformity across platforms is something you must verify, not assume.


Common Mistakes

  1. Assuming expect/actual guarantees identical behaviour. The compiler checks the signature, not the semantics. Two actuals can diverge behaviourally, producing platform-dependent bugs.
  1. Delegating behaviour-that-must-match to differing platform APIs. Rounding, formatting, date parsing, and collation vary across platforms. Implement anything that must be uniform in common code, not per platform.
  1. Putting platform-specific code in commonMain. Common code may only use APIs available on every target; a JVM-only call there breaks the build for other targets. Move it behind an expect.
  1. Forgetting an actual for a target. Every expect needs an actual on every target, or that target will not compile. Omitting one is a build failure, not a silent default.
  1. Mismatched expect/actual signatures. An actual whose parameters or return type differ from the expect is rejected. The two must match exactly.
  1. Testing on only one platform. A test suite run on a single target cannot catch divergence on another. Run commonTest against every target.
  1. Overusing expect/actual for things that could be common. If a piece of logic can be written portably, keep it in commonMain; reserve expect for what genuinely must be platform-specific.
  1. Leaking a platform type through a common signature. A common expect that returns a platform-only type cannot be expressed in common code. Return common types and convert inside the actual.
  1. Ignoring floating-point and locale differences. Number and text handling differ subtly across targets; assuming byte-for-byte identical output invites reconciliation mismatches.

Best Practices

  • Keep any behaviour that must be identical across platforms in commonMain, implemented once, rather than delegating to platform APIs that differ.
  • Reserve expect/actual for genuinely platform-specific capabilities, and write everything portable as common code.
  • Match every expect with an actual on every target, keeping signatures exactly aligned.
  • Run the shared test suite (commonTest) on all targets so behavioural divergence fails the build rather than shipping.
  • Return common types from expect declarations, converting platform types inside the actual, so common code stays portable.
  • Pin the behavioural contract of each expect precisely in documentation and tests, since the compiler only checks the signature.
  • Structure the project with a thin platform layer and a thick common layer, maximising shared, tested code.
  • Treat cross-platform uniformity of numbers, dates, and text as something to verify explicitly, never to assume.

Practice Exercises

  1. Model expect/actual with an interface: write a Platform abstraction, two implementations, and a common greeting function, and confirm the shared function runs with each.
  1. Write common logic that generates records using an injected ID abstraction, supply a deterministic sequential implementation, and confirm the shared code produces the expected IDs.
  1. Reproduce the divergent-actual flaw: give two implementations of a rounding abstraction different half-way rules, show they disagree on 2.5 but agree on 3.5, then describe how moving the rule into common code fixes it.
  1. Explain, with a short example, why platform-specific code cannot live in commonMain and must be reached through an expect declaration instead.