Kotlin Expect and Actual: A Practical Guide for Beginners and Intermediates šŸŽÆ

beginner
16 min

Kotlin Expect and Actual: A Practical Guide for Beginners and Intermediates šŸŽÆ

Welcome to our detailed tutorial on Kotlin's expect and actual! This concept is a powerful tool for ensuring type safety in your code, making it more robust and easier to maintain. Let's dive in! 🤿

What are expect and actual? šŸ’”

In Kotlin, expect and actual are used in contracts to declare and verify expected types. They help in preventing type mismatches at compile-time, enhancing code reliability.

kotlin
interface MyContract { fun someFunction(input: String): Int } class MyClass : MyContract { override fun someFunction(input: String) = input.length } // Usage with expect-actual fun main() { expect { it is MyContract } // Declare the expected contract val myObject = MyClass() as MyContract // Cast the object val result = myObject.someFunction("Hello") // Call the function actual { it is Int } // Verify the returned type is Int }

šŸ“ Note: Kotlin will throw a compile-time error if the expected and actual types don't match.

Real-world Application šŸ“

Let's consider a use case where you have a function that accepts any data type, but you know it will only receive certain types based on the context. With expect and actual, you can ensure that only the expected data types are passed.

kotlin
interface DataTypeContract { data class StringData(val data: String) : DataTypeContract data class IntData(val data: Int) : DataTypeContract } fun processData(data: Any, contract: DataTypeContract.() -> Unit) { when (contract()) { is DataTypeContract.StringData -> println(data.data.length) is DataTypeContract.IntData -> println(data.data * 2) } } // Using expect-actual fun main() { expect { it is DataTypeContract } processData("Hello" as Any, DataTypeContract::StringData) expect { it is Int } processData(10, DataTypeContract::IntData) }

Quiz Time! šŸŽÆ

Quick Quiz
Question 1 of 1

What are `expect` and `actual` used for in Kotlin?

Remember, the key to mastering expect and actual is understanding the need for type safety in your code and using these concepts to ensure that your functions only accept and return the expected data types. Keep practicing, and happy coding! šŸ’»

Next Lesson: Kotlin Data Classes āœ