What is expect and actual in Kotlin Multiplatform: Simple Explanation
expect declares a platform-dependent API without implementation, while actual provides the platform-specific implementation. This lets you write common code that works on different platforms by linking expected declarations to their actual versions.How It Works
Imagine you want to write a recipe that works in different kitchens, but each kitchen has its own tools. The expect keyword is like writing the recipe steps without naming the exact tools. The actual keyword is like specifying the exact tool available in each kitchen to follow the recipe.
In Kotlin Multiplatform, expect declares a function, class, or property that you want to use in your shared code but don't implement it there. Instead, you provide an actual implementation for each platform (like Android, iOS, or JVM). When you build your app, Kotlin links the expect declarations to the right actual implementations automatically.
This system helps you write common logic once and handle platform differences cleanly, avoiding duplicate code and making maintenance easier.
Example
This example shows how to declare an expect function in common code and provide actual implementations for JVM and JavaScript platforms.
// Common code (shared module) expect fun platformName(): String // JVM actual implementation actual fun platformName(): String { return "JVM" } // JavaScript actual implementation actual fun platformName(): String { return "JavaScript" } fun greet(): String { return "Hello from ${platformName()}!" } fun main() { println(greet()) }
When to Use
Use expect and actual when you want to share code across platforms but need platform-specific details. For example, accessing device features, file systems, or UI elements that differ between Android, iOS, or desktop.
This approach is great for libraries or apps targeting multiple platforms, letting you keep most code common and only write platform-specific parts where necessary.
Key Points
- expect declares what you want to use without implementation.
- actual provides the real implementation for each platform.
- This mechanism enables clean multiplatform code sharing.
- It helps handle platform differences without duplicating all code.