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

Bookmarks in commonMain has an empty Storage slot; with expect and actual, the compiler fixes one iOS actual into it; with an interface, three identical panels: the Android app's start hands PrefsStorage into its Bookmarks, the iOS app's start hands DefaultsStorage into its own, and a test hands in FakeStorage commonMain Bookmarks Storage compileriOS actualone per target Android start iOS start a test Bookmarks Bookmarks Bookmarks PrefsStorage DefaultsStorage FakeStorage

Scroll sideways to see the full diagram.

  1. Bookmarks, in commonMain, needs a Storage: an interface it takes in its constructor instead of creating one.

    Step 1 of 5
  2. With expect, the compiler fixes exactly one actual into each target's build: one per target, chosen before the app runs.

    Step 2 of 5
  3. With an interface, the same Bookmarks is built in three places, and each platform implements Storage with its own store. Predict: who puts one in?

    Step 3 of 5
  4. Each app's start: Android's hands in PrefsStorage, iOS's DefaultsStorage. That's dependency injection: what an object needs comes from outside.

    Step 4 of 5
  5. A test builds Bookmarks with no phone and hands in a fake: a small, working Storage that 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 needUse
A small platform fact, like a name or a new ID, in a project without a DI frameworkexpect fun or expect val
An existing platform class under a common nameexpect class, kept with actual typealias: "on this platform, the expected class is this existing one"
A service: storage, network, sensorsan interface, handed in
Anything platform-specific, once the project uses a DI frameworkthat 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

Your iOS app needs two storages on iOS: NSUserDefaults for settings and an encrypted store for passwords. Storage is an expect class with one actual in iosMain. What's the problem?

Right. expect/actual: exactly one implementation per target.

Not quite. An actual in iosMain can use Apple's APIs; the limit is one actual per target.

Not quite. The compiler accepts exactly one actual per target; a second one for the same target is an error. Re-read that part ↑

Why does the test for Bookmarks run without SharedPreferences or NSUserDefaults?

Right. A fake is handed in, like any implementation.

Not quite. Nothing is skipped: Bookmarks calls whatever storage it was handed, here the fake.

Not quite. commonTest is compiled for every target; the test passes a fake instead of a platform store.

Your project already uses Koin, and you now need the platform's name in common code. Which way do Kotlin's docs recommend?

Right. One way of handing things in, not two.

Not quite. commonMain can't call Android's APIs (puzzle 18). Re-read that part ↑

Not quite. expect suits a small fact in a project without a DI framework; with one, the docs advise against mixing two ways of handing things in. Re-read that part ↑

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.