Connect to platform-specific APIs
If you’re developing a multiplatform application that needs to access platform-specific APIs that implement the required functionality, use the Kotlin mechanism of expected and actual declarations.
With this mechanism, a common source set defines an expected declaration, and platform source sets must provide the actual declaration that corresponds to the expected declaration. This works for most Kotlin declarations, such as functions, classes, interfaces, enumerations, properties, and annotations.
Here's another example of code sharing and interaction between the common and platform logic in a minimalistic logging framework.
actual declaration will look like this.
Rules for expected and actual declarations
The main rules regarding expected and actual declarations are:
An expected declaration is marked with the
expectkeyword; the actual declaration is marked with the
actualdeclarations have the same name and are located in the same package (have the same fully qualified name).
expectdeclarations never contain any implementation code.
During each platform compilation, the compiler ensures that every declaration marked with the
expect keyword in the common or intermediate source set has the corresponding declarations marked with the
actual keyword in all platform source sets. The IDE provides tools that help you create the missing actual declarations.
If you have a platform-specific library that you want to use in shared code while providing your own implementation for another platform, you can provide a
typealias to an existing class as the actual declaration: