Skip to main content

03 - KMP Shared Module: Interfaces, expect/actual and Koin

How to structure the KMP shared module: layers, interfaces instead of expect/actual, Koin to choose implementations, and tests without an emulator.

What do you think about this article?

At a Glance

How to structure the KMP shared module: layers, interfaces instead of expect/actual, Koin to choose implementations, and tests without an emulator.

Shared module architecture in KMP: interfaces, expect/actual and Koin

The shared module of a Kotlin Multiplatform project stays maintainable if you follow a single rule: the common code depends on interfaces, and only the configuration knows which platform implementation to use. The rest - the layers, Koin, tests without an emulator - is a consequence of that choice. The official documentation itself says so: as a general rule it is better to use the standard language constructs instead of expect/actual declarations, which are mainly needed in the dependency injection setup.

I assume you already have a project configured as in the second article of the series. On this machine Kotlin is not installed: no listing was compiled or run, they are all schemas to adapt and compare with the pages cited in the Sources. Where an API detail is uncertain, I say so in the text instead of feigning confidence.

Three layers and one direction of dependency

A shared module becomes a tangle when the code that computes a price imports the HTTP client. The remedy is the same as in any layered architecture: the domain contains models, interfaces and use cases and imports nothing external; the data layer implements the domain's interfaces with Ktor and SQLDelight; the presentation exposes state to the UI using the use cases.

shared/src/commonMain/kotlin/com/example/app/
├── domain/
│   ├── model/User.kt
│   ├── repository/UserRepository.kt   # interface only
│   └── usecase/GetUsersUseCase.kt
├── data/
│   ├── network/UserApi.kt             # Ktor
│   ├── local/UserLocalSource.kt       # SQLDelight
│   └── repository/UserRepositoryImpl.kt
├── presentation/UserListViewModel.kt
└── di/
    ├── Modules.kt                     # common Koin modules
    └── PlatformModule.kt              # expect: platform modules

The arrow always goes from the outside towards the domain: data imports domain, never the opposite. In KMP this rule has one more advantage compared with an Android app: everything in domain has no platform dependencies, so it compiles and is tested on any target. The principle is the same one described in The dependency rule for the Java backend, and the ports and adapters mechanism is analysed in The port in the domain, the adapter in infrastructure: the language changes, not the idea.

Where expect/actual is really used

An expect declares in the common code a function, property or class without an implementation; each platform provides an actual with the same name and in the same package. The compiler checks that the pair exists for every target. The mechanism is powerful and for that reason it gets abused: every expect is a duplication to maintain in all the source sets. A useful criterion: use it when the behaviour really varies by platform, not when the implementation of a rule varies.

// WRONG: a business rule does not vary by platform
expect fun calculateDiscount(price: Double, percentage: Int): Double

// RIGHT: it lives in commonMain, once
fun calculateDiscount(price: Double, percentage: Int): Double =
    price * (100 - percentage) / 100.0

The discount is a pure calculation: the formula is the same on an iPhone, on a Pixel and on the desktop, and an expect here multiplies by three the places where a bug can hide. The case where expect is appropriate is access to an operating system service that has no common equivalent. But even then the documentation's advice is not to expose expect classes directly (they are in Beta): better an expect function that returns an interface, or an interface provided by DI.

One common interface, two implementations

Let us take a concrete case: saving the theme chosen by the user. On Android you use SharedPreferences, on iOS NSUserDefaults. The domain must know about neither, so it defines a small interface, and the use case receives it in its constructor.

// commonMain - domain
interface KeyValueStore {
    fun getString(key: String): String?
    fun putString(key: String, value: String)
}

class SaveThemeUseCase(private val store: KeyValueStore) {
    fun execute(theme: String) = store.putString("theme", theme)
    fun current(): String = store.getString("theme") ?: "light"
}

// androidMain
class AndroidKeyValueStore(context: Context) : KeyValueStore {
    private val prefs = context.getSharedPreferences("app", Context.MODE_PRIVATE)
    override fun getString(key: String) = prefs.getString(key, null)
    override fun putString(key: String, value: String) {
        prefs.edit().putString(key, value).apply()
    }
}

// iosMain
class IosKeyValueStore : KeyValueStore {
    private val defaults = NSUserDefaults.standardUserDefaults
    override fun getString(key: String) = defaults.stringForKey(key)
    override fun putString(key: String, value: String) {
        defaults.setObject(value, forKey = key)
    }
}

The detail that makes the difference is that SaveThemeUseCase imports neither android.content.Context nor NSUserDefaults: it depends on KeyValueStore. The Android implementation receives the Context in its constructor, and this avoids the anti-pattern of an expect class that takes Any? and converts it with a cast, because the cast moves to run time an error the compiler could give you at compile time. The exact syntax of the Foundation APIs (stringForKey, setObject) has to be checked against the Kotlin version in use: they are automatically generated bindings.

Koin: the point where the implementation is chosen

It remains to decide who creates AndroidKeyValueStore or IosKeyValueStore. A dependency injection container does it, and for KMP Koin is a common choice because it is written in Kotlin and works in common code. The Koin documentation for KMP suggests keeping the platform modules behind an expect declaration, so that the common code only knows that there is a module to register.

// commonMain/di/Modules.kt
import org.koin.core.context.startKoin
import org.koin.core.module.Module
import org.koin.core.module.dsl.singleOf
import org.koin.dsl.KoinAppDeclaration
import org.koin.dsl.module

val domainModule = module {
    singleOf(::SaveThemeUseCase)
    singleOf(::GetUsersUseCase)
}

val dataModule = module {
    single<UserRepository> { UserRepositoryImpl(get(), get()) }
}

expect fun platformModule(): Module

fun initKoin(config: KoinAppDeclaration? = null) {
    startKoin {
        config?.invoke(this)
        modules(domainModule, dataModule, platformModule())
    }
}

Two choices to explain. singleOf(::SaveThemeUseCase) is a shortcut that leaves Koin the task of resolving the constructor parameters: it works as long as you have a single implementation for each type, and that is why KeyValueStore does not appear here, but in the platform module. The second point is that platformModule is an expect function, as in the Koin documentation, and not a property: if you need the Android Context, the function will receive it from Koin with androidContext() at startup. The config parameter lets each platform add its own things, such as the logger or the context, without the common code knowing them.

// androidMain/di/PlatformModule.android.kt
actual fun platformModule(): Module = module {
    single<KeyValueStore> { AndroidKeyValueStore(androidContext()) }
}

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        initKoin { androidContext(this@MyApplication) }
    }
}

// iosMain/di/PlatformModule.ios.kt
actual fun platformModule(): Module = module {
    single<KeyValueStore> { IosKeyValueStore() }
}

object IosKoin {
    fun start() = initKoin()
}

This is the only point where an actual appears: the choice of the concrete implementation per platform. androidContext() requires the dependency io.insert-koin:koin-android in the Android source set. For iOS I chose an object IosKoin because from Swift it is called as IosKoin.shared.start() and does not depend on the name of the file that contains the function. From Swift, the Koin documentation reminds us, you cannot instead call reified functions such as get<T>(): you need helpers written in Kotlin.

// iosMain - helper for Swift (schema taken from the Koin documentation)
class ThemeHelper : KoinComponent {
    private val saveTheme: SaveThemeUseCase by inject()
    fun current(): String = saveTheme.current()
}

// iosApp/iOSApp.swift
import SwiftUI
import Shared

@main
struct iOSApp: App {
    init() {
        IosKoin.shared.start()
    }
    var body: some Scene {
        WindowGroup { ContentView() }
    }
}

The Swift side is short precisely because Koin lives entirely in Kotlin. The call in the app's init ensures that Koin is started before any screen asks for a ThemeHelper: reversing the order produces a run-time error, not a compile-time one, because the container is a service that starts at run time.

A shared ViewModel you can test

The screen state lives in a StateFlow, which the platforms observe. The ViewModel below is a plain class, not an Android ViewModel: it has a scope that it governs itself and a method to close it. The device that makes it testable is that the dispatcher is a parameter with a default value.

// commonMain - presentation
sealed interface UserListState {
    data object Loading : UserListState
    data class Success(val users: List<User>) : UserListState
    data class Error(val message: String) : UserListState
}

class UserListViewModel(
    private val getUsers: GetUsersUseCase,
    dispatcher: CoroutineDispatcher = Dispatchers.Main
) {
    private val scope = CoroutineScope(SupervisorJob() + dispatcher)
    private val _state = MutableStateFlow<UserListState>(UserListState.Loading)
    val state: StateFlow<UserListState> = _state.asStateFlow()

    fun loadUsers() {
        scope.launch {
            _state.value = UserListState.Loading
            _state.value = try {
                UserListState.Success(getUsers.execute())
            } catch (e: CancellationException) {
                throw e
            } catch (e: Exception) {
                UserListState.Error(e.message ?: "Unknown error")
            }
        }
    }

    fun onCleared() = scope.cancel()
}

If the dispatcher were hard-wired to Dispatchers.Main, a test on the JVM would fail because the main dispatcher does not exist outside a platform with a graphical interface; injecting it lets the test pass a controlled one. The catch (e: CancellationException) block rethrows the cancellation, which in Kotlin is an exception and not an error to show the user. The sealed interface makes the when on the state exhaustive, so if you add a fourth state the compiler points out every place to update.

Testing in commonTest, without an emulator

With an interface in place of every dependency, a test needs neither Ktor, nor a database, nor a simulator: a fake that implements the interface is enough. The test uses runTest from kotlinx-coroutines-test, a dependency to add to commonTest, and a StandardTestDispatcher that shares the test's scheduler.

// commonTest
class FakeUserRepository(private val users: List<User>) : UserRepository {
    override suspend fun getUsers() = users
    override suspend fun getUserById(id: Long) = users.firstOrNull { it.id == id }
    override suspend fun saveUser(user: User) = user
}

class UserListViewModelTest {
    private val users = listOf(User(1, "Anna", "anna@example.com"), User(2, "Luca", "luca@example.com"))

    @Test
    fun loadUsersProducesSuccess() = runTest {
        val dispatcher = StandardTestDispatcher(testScheduler)
        val viewModel = UserListViewModel(GetUsersUseCase(FakeUserRepository(users)), dispatcher)

        viewModel.loadUsers()
        advanceUntilIdle()

        val state = assertIs<UserListState.Success>(viewModel.state.value)
        assertEquals(2, state.users.size)
    }
}

The test was not run (Kotlin is not present). The step that holds the test up is advanceUntilIdle(): with a StandardTestDispatcher the coroutine launched by loadUsers() does not start until the scheduler advances; without this line the state stays Loading and the assertion fails. Using FakeUserRepository instead of a mocking library is a choice: in commonTest not all mocking libraries work on iOS, whereas a hand-written class works everywhere.

Rules to take away

  • The domain stays pure: no imports of Ktor, SQLDelight, Android or iOS.
  • Everything that varies by platform goes through an interface; expect lives only in the DI configuration.
  • Tests live in commonTest and run on the fastest target; the iOS ones concern only what is truly native.
  • Coroutines are not exposed to Swift without an adapter: Swift export (Alpha) or third-party tools, and remember that a Flow is not a Swift type.

The four rules are ordered by the cost of violating them. The first and the second are the ones that, if broken, force you to rewrite code when you add a third target; the last two concern working comfort. If you have to choose which to apply first on a project already under way, start from the domain: remove one platform import at a time and route each case through an interface.

Frequently asked questions

When should I use expect/actual instead of an interface?

Almost never in domain code. The official documentation recommends the standard language constructs, because an interface allows several implementations per platform and fakes in tests. expect/actual is mainly needed in the dependency injection setup.

Does Koin work on iOS?

Yes: the Koin documentation for Kotlin Multiplatform describes the startup from iOS and Koin's code runs with the current Kotlin/Native memory manager. From Swift you cannot call reified functions such as get<T>(), so you need a small helper in Kotlin.

What you can do now

You can organise the shared module in three layers with the dependency pointing towards the domain, recognise when an expect is superfluous, isolate a platform dependency behind an interface and choose the implementation with Koin. You can write a ViewModel with an injected dispatcher and test it in commonTest without an emulator. The overall picture and the stability levels are in the first article of the series.

Sources

  • Expected and actual declarations (kotlinlang.org) - recommendation to use the standard constructs, DI, Beta status of expect classes; consulted on 2026-11-12.
  • Use platform-specific APIs (kotlinlang.org) - common interface with per-platform implementations; consulted on 2026-11-12.
  • Koin for Kotlin Multiplatform (insert-koin.io) - platformModule() as an expect function, singleOf, KoinComponent helper for Swift; consulted on 2026-11-12.
  • kotlinx-coroutines-test (kotlinlang.org) - runTest, StandardTestDispatcher, advanceUntilIdle; page reached on 2026-11-12, the details of the listings were not tried.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects