Expect and Actual in Kotlin Multi platform Mobile
In Kotlin/Native we can write platform specific code at any layer of code and most important at any time during development. It is not like React Native or Flutter where we get tied up into their environment. You can go through previous blog if you want to check how kotlin/native works and how to write a simple example it.
UI in Kotlin/Native
In Kotlin/Native UI is written native code (Swift/Objective C or Kotlin/java) so at that layer we are free to write native code when ever and for what ever we want.
Business Logic and Network Layer
In Kotlin/Native business logic layer is the common layer developed in Kotlin/Native code. It is shared by both android and IOS apps. In this layer we have to write Kotlin/Native code. But at any point of development if you want to add native code than it is possible here. For implementing that we need to use expect and actual keywords
expect
In shared module whenever we want to write a platform specific code we have to use expect keyword. expect keyword in the signature of function means it will be implemented separately using Android and IOS specific code.
package com.sharedmoduleexpect fun getNameOfPlatform(): Stringclass Greeting{
fun sayWelcome(): String = "Welcome, ${getNameOfPlatform()}"
}
Here Greeting class is invoking expect fun getNameOfPlatform(). that function is only having declaration. We need to provide implementation to it.
actual
expect function will be implemented using actual keyword separately on both the platforms
Android specific code is in androidMain/kotlin folder (android.kt file)
package com.sharedmoduleimport android.os.Buildactual fun getNameOfPlatform(): String {
return "Android ${Build.VERSION.RELEASE}"
}
Similarly the IOS specific code is in iosMain/kotlin folder (ios.kt file)
package com.sharedmoduleimport platform.UIKit.UIDeviceactual fun getNameOfPlatform(): String {
return "${UIDevice.currentDevice.systemName()}
${UIDevice.currentDevice.systemVersion()}"
}
Conclusion
We can write Native code to create UI and in shared code also where ever we want we can write native code. This is the beauty of Kotlin/Native we we will never stuck in the Framework like React Native and Flutter.