Kotlin expect and actual Keywords

Multiplatform development

The expect and actual keywords are special keywords used in Kotlin Multiplatform projects. They take advantage of Kotlin’s design for use across multiple platforms.

In a Kotlin Multiplatform project, code is generally shared across multiple platforms such as JVM, Android, iOS, and JavaScript. However, some cases require a platform-specific implementation. In such cases, the expect and actual keywords can be used to provide different implementations for each platform.

  • expect
    • The expect keyword is used to declare how a particular interface, class, or function should be implemented on a platform.
    • In other words, it defines the expected implementation. It is generally used in shared code and defines APIs that must be provided by a specific platform.
  • actual
    • The actual keyword maps to the expect keyword and provides the concrete implementation of that interface, class, or function.
    • This is the specific implementation provided per platform. Therefore, platform-specific code can be written for each platform.

The following is a simple example that uses the expect and actual keywords to provide different implementations by platform.

// common module
expect fun platformSpecificFunction(): String

// JVM module
actual fun platformSpecificFunction(): String {
    return "This is the JVM implementation"
}

// iOS module
actual fun platformSpecificFunction(): String {
    return "This is the iOS implementation"
}

// Usage
fun main() {
    println(platformSpecificFunction()) // Output depends on the platform
}

In the example above, platformSpecificFunction is declared with expect in the shared common module. The actual implementation for each platform is then provided with the actual keyword. As a result, the appropriate implementation is used each time the code runs on a platform.