expect/actual
- Kotlin course
- Expert
- Lesson 27/47
- 5 min
Learn platform code with expect/actual.
What is expect/actual?
expect/actual is the mechanism in KMP that manages platform-specific code. expect declares a contract in commonMain; each target implements it with actual.
For example expect fun platformName(): String is written in commonMain. The iOS target defines actual fun platformName(): String = "iOS", the JVM target actual fun platformName(): String = "JVM". The compiler picks the right actual for each target. This way shared code can call the function without knowing the platform.
An actual example
An actual implementation is written in the target's source set. For the JVM target that is jvmMain, for iOS it is iosMain.
Example: actual fun platformName(): String = "JVM". The signature of the actual must match the expect exactly; the type, parameters and name must agree. Otherwise the compiler errors. This strictness keeps shared code consistent across targets. In this lesson we model the concept with a platformName function.
Practice Write platformName
Define fun platformName(): String. It should return "JVM". In main, write println(platformName()).
Starter code
// add the platformName function
fun main() {
// print the platform name
}Sample solution
fun platformName(): String = "JVM"
fun main() {
println(platformName())
}Expected output
JVM
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the expect/actual parts
| Term | Meaning |
|---|---|
expect fun |
contract in commonMain |
actual fun |
impl in target set |
expect val |
constant in commonMain |
actual val |
value in target set |
2 Where is the actual keyword written?
actual is target-specific.- iosMain Correct answer
- commonMain
- build.gradle
- test
Explanation: actual is written in the target source set; e.g. iosMain.
3 Complete the actual declaration
____ fun log(msg: String) { println(msg) }
actual fun log(msg: String) { println(msg) }
Explanation: actual implements the log function in the target set.