Junior — Middle
What is the difference between the expect/actual mechanism and standard interfaces in programming?
sobes.tech AI
Answer from AI
The expect/actual mechanism is used in Kotlin Multiplatform to define platform-dependent code. The key difference from standard interfaces is that:
- expect declares an API without implementation (for example, a function or class), which expects a platform-specific implementation.
- actual provides a concrete implementation for a specific platform (JVM, JS, Native).
Unlike interfaces, which define a contract and require implementation in classes, expect/actual separates declaration and implementation across platforms, allowing you to write common code with platform-dependent details.
Example:
// commonMain
expect fun getPlatformName(): String
// androidMain
actual fun getPlatformName() = "Android"
// iosMain
actual fun getPlatformName() = "iOS"
Thus, expect/actual helps create multiplatform libraries with different implementations for each platform, whereas interfaces simply define a contract for classes within a single platform.