CoursesKotlin Multiplatform, from the compiler up
Puzzle 22 · 23 of 32
expect/actual or an interface
Puzzle 3 kept a small promise with expect and actual, and said bigger platform services usually go behind an interface instead. Here's what that means in a real module, how the right implementation is handed in on each platform, and how to choose.
All puzzles in this course
The problem
Puzzle 3 kept a promise: common code declared expect fun platformName(), and each platform's source set kept it with an actual. It also said that for bigger platform services, an interface handed in from outside does the same job and is easier to test.
Now a real case. Your shared Bookmarks class must save a user's bookmarks. On Android, the app keeps small values in SharedPreferences. On iOS, Apple's own key-value store is called NSUserDefaults. Bookmarks lives in commonMain, so by puzzle 18 it can't call either. And your test for Bookmarks must run without either store. Do you write expect, or an interface? And if an interface, who creates the right implementation, and when?
See it
Scroll sideways to see the full diagram.
Bookmarks, in commonMain, needs aStorage: an interface it takes in its constructor instead of creating one.Step 1 of 5With
expect, the compiler fixes exactly oneactualinto each target's build: one per target, chosen before the app runs.Step 2 of 5With an interface, the same
Bookmarksis built in three places, and each platform implementsStoragewith its own store. Predict: who puts one in?Step 3 of 5Each app's start: Android's hands in
PrefsStorage, iOS'sDefaultsStorage. That's dependency injection: what an object needs comes from outside.Step 4 of 5A test builds
Bookmarkswith no phone and hands in a fake: a small, workingStoragethat keeps values in memory, so the test can check what was saved.Step 5 of 5
The building block
Start with the interface. commonMain declares what Bookmarks needs, and takes it as a constructor parameter instead of creating it:
// commonMain
interface Storage {
fun save(key: String, value: String)
fun load(key: String): String?
}
class Bookmarks(private val storage: Storage) {
fun add(url: String) = storage.save("last", url)
}
Each platform's source set implements it with its own APIs, and the shared module's test source set adds one more:
// androidMain
class PrefsStorage(context: Context) : Storage { /* SharedPreferences */ }
// iosMain
class DefaultsStorage : Storage { /* NSUserDefaults */ }
// commonTest
class FakeStorage : Storage {
val saved = mutableMapOf<String, String>()
override fun save(key: String, value: String) { saved[key] = value }
override fun load(key: String) = saved[key]
}
Bookmarks never creates its storage: it's handed one. That pattern is dependency injection: an object receives what it depends on from outside, instead of creating it itself. Here the outside is each app's start, which Kotlin's docs call the entry point. The Android app builds it in its Application's onCreate(), the iOS app at its start, in Swift, and a test in commonTest:
Bookmarks(PrefsStorage(this)) // Android: Application.onCreate()
// Bookmarks(storage: DefaultsStorage()) // iOS: the app's start, in Swift
Bookmarks(FakeStorage()) // a test
A fake is a small, working implementation of an interface written for tests: it keeps data in memory, so a test can check what Bookmarks saved without a phone, a file or a store.
Could an expect class Storage do the same? It can give each target its implementation, but the compiler merges each expect with exactly one actual per target. A test compiled for iOS gets the iOS actual, so there's no place for a fake, and no way to have two storages on one platform. Kotlin's docs also mark expected classes as Beta: the compiler warns when you use them.
As an app grows, writing every constructor call by hand at the start gets long. A dependency injection framework builds the objects for you and hands each one what it needs, from rules you write once; Koin is one that works in common code. Its rules are ordinary Kotlin in commonMain, except the few that name a platform class such as DefaultsStorage: those live in androidMain and iosMain. Kotlin's docs say that then expect and actual are needed only to configure the framework, and they give one firm piece of advice: if your project already uses dependency injection, keep using it for platform parts too, rather than adding expect and actual functions next to it, so you "avoid mixing two different ways of injecting dependencies". How Koin's rules are written is module 8's subject (coming soon).
How to choose:
| You need | Use |
|---|---|
| A small platform fact, like a name or a new ID, in a project without a DI framework | expect fun or expect val |
| An existing platform class under a common name | expect class, kept with actual typealias: "on this platform, the expected class is this existing one" |
| A service: storage, network, sensors | an interface, handed in |
| Anything platform-specific, once the project uses a DI framework | that framework, with expect and actual only inside its setup |
The analogy
The shared handbook from puzzle 3 again. "Call the local tax office" is a blank each country fills in once, before printing: fine for one phone number. But for "the courier who delivers our parcels", the handbook says only what a courier must do, and each office hires its own and introduces them on the first day. During training, a stand-in courier carries empty boxes, so nobody has to wait for a real delivery.
Check yourself
Sources
- Kotlin docs: Use platform-specific APIs ("you can define an interface in common code that holds abstract platform-independent declarations and then provide implementations of that interface in the platform source sets"; "To inject the appropriate platform implementations when using a common interface, you can choose one of the following options:", then the list "Use expected and actual functions", "Provide implementations through different entry points", "Use a dependency injection framework"; "Koin is a dependency injection framework that supports Kotlin Multiplatform";
single<Platform> { IOSPlatform() }; "We recommend continuing to use DI if you already have it in your project, rather than using the expected and actual functions manually. This way, you can avoid mixing two different ways of injecting dependencies.") - Kotlin docs: Expected and actual declarations ("Expected and actual classes are in Beta"; "the Kotlin compiler will warn you about the Beta status of the feature"; "This means that expected and actual declarations are only needed in the configuration of the DI framework"; "With interfaces, you don't limit your design to one implementation per target platform. Also, it's much easier to substitute a fake implementation in tests or provide multiple implementations on a single platform.";
actual typealias MyDate = java.time.LocalDate)
What you now know
expect/actual gives exactly one implementation per target, merged by the compiler: right for small facts and for pointing at an existing platform class. For a service, declare an interface in commonMain, implement it per platform, and hand the implementation in from outside, at the app's start or through a dependency injection framework such as Koin. Then a test can hand in a fake; and once a project uses such a framework, platform parts go through it too, not through a second way.
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.