WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Guru · question 84 of 100

In the context of multiplatform development, explain how Kotlin’s expect and actual keywords help achieve platform-specific implementations while maintaining a shared codebase.?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

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.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics