Kotlin Multiplatform, from the compiler up · Puzzle 3 · 4 of 16
A promise and its keepers
In puzzle 1, common code couldn't call a platform's own APIs. But shared logic sometimes needs a small platform fact, like which phone it's running on. Here's how it asks without knowing.
The problem
In puzzle 1, common code could only use what every target has. But your shared logging code wants to print which platform it's on: "Android 34" or "iOS 17". Each platform has its own way to tell, and common code can't call either. How does common code use something only the platforms have?
See it
Common code makes a promise:
platformName(), marked expect, with no body. It can call it without knowing how it works.Step 1 of 4Each platform keeps the promise with an actual, written with its own APIs: Android's build number, Apple's system version.
Step 2 of 4When the compiler builds the Android target, it plugs in Android's actual. Predict: what if a target has no actual?
Step 3 of 4That target's build fails. The compiler checks every promise is kept, so none can be forgotten.
Step 4 of 4
The building block
Common code makes a promise. It declares what it needs, without a body, marked expect:
// commonMain
expect fun platformName(): String
Then every platform source set keeps that promise with an actual declaration, using its own APIs:
// androidMain
actual fun platformName(): String = "Android ${Build.VERSION.SDK_INT}"
// iosMain
actual fun platformName(): String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
Common code calls platformName() like any function. When the compiler builds a target, it plugs in that target's actual. And it checks: if one target has no actual, that target's build fails, so a promise can't be forgotten.
expect and actual work best for small things like this. For bigger platform services, like storage or a network client, the usual choice is an interface in common code with one implementation per platform, handed in from outside: it does the same job, and in a test you can hand in a fake.
The analogy
The shared handbook from puzzle 1 says: "Call the local tax office." It doesn't say which. Each country's office fills in its own number. Before the handbook is printed for a country, someone checks that number is filled in.
Check yourself
Sources
- Kotlin docs: Expected and actual declarations ("Expected and actual declarations allow you to access platform-specific APIs from Kotlin Multiplatform modules. You can provide platform-agnostic APIs in the common code.")
What you now know
An expect declaration in common code is a promise; every platform source set keeps it with an actual declaration. The compiler checks that every target has one. For anything bigger, an interface implemented per platform does the same job and is easier to test.
Answer every question above correctly to unlock the next puzzle.
Something wrong or unclear on this page? Tell me: a puzzle that didn't click is a bug in the puzzle.