Kotlin is a multiplatform programming language that allows developers to write a single codebase and compile it into multiple platforms, such as JVM, Android, iOS, and JavaScript. However, not all platform-specific features can be relied upon to be accessible on all platforms, and this is where the ‘expect‘ and ‘actual‘ keywords come to help.
‘expect‘ and ‘actual‘ are two keywords in Kotlin that enable developers to write platform-specific implementations without breaking the shared codebase. The ‘expect‘ keyword is used to define the expected behavior or interface of a function, class, or variable for a specific platform. On the other hand, the ‘actual‘ keyword is used to provide an actual implementation of the expected behavior for a particular platform.
Here’s a simple example of how these keywords can be used:
// In common code
expect fun getTimeStamp(): Long
// In Android-specific code
actual fun getTimeStamp(): Long {
return System.currentTimeMillis()
}
// In iOS-specific code
actual fun getTimeStamp(): Long {
return NSDate().timeIntervalSince1970.toLong()
}
In the above example, the ‘expect‘ keyword is used to define the functionality of ‘getTimeStamp()‘ that should be implemented on each platform. In this case, the function should return a ‘Long‘ timestamp value.
Meanwhile, the ‘actual‘ keyword is used to provide platform-specific implementations of the ‘getTimeStamp()‘ function. On Android devices, ‘System.currentTimeMillis()‘ is used, while on iOS devices, ‘NSDate().timeIntervalSince1970.toLong()‘ is used to get the current timestamp.
By using these keywords, developers can maintain a single codebase while still having the ability to provide platform-specific implementations. This is useful when there is a need to use platform-specific features or when there are differences in behavior between different platforms.
In summary, Kotlin’s ‘expect‘ and ‘actual‘ keywords are powerful tools that allow developers to achieve platform-specific implementations while maintaining a shared codebase. These keywords allow developers to write code once and still support multiple platforms with minimal effort.