Welcome to the Kotlin Scope of Extensions tutorial! In this lesson, we'll explore how to extend the functionality of existing classes using Kotlin's powerful extension functions. By the end, you'll be able to write your own extensions, making your code more reusable and easier to maintain.
Extension functions are functions that can be called on any receiver type as if they were methods of that type. They allow us to add new functionality to existing classes without modifying the original source code.
fun Int.isEven(): Boolean {
return this % 2 == 0
}
fun main() {
val number = 10
println("Is $number even? ${number.isEven()}") // Prints: Is 10 even? true
}In the example above, we defined an extension function isEven() for the Int type. We can now call this function on any Int variable, just like it's a built-in method.
The receiver type is the type that will receive the extension function. It can be any Kotlin class, interface, or even a top-level type like Int or String.
class MyClass(val value: Int) {
fun MyClass.isEven(): Boolean {
return value % 2 == 0
}
}
val myInstance = MyClass(10)
println("Is myInstance even? ${myInstance.isEven()}") // Prints: Is myInstance even? trueIn this example, we defined an extension function isEven() for the MyClass type. Now we can call it directly on any instance of MyClass.
Besides functions, we can also create extension properties using val or var.
val String.lengthInWords: Int
get() = this.length / 3
fun main() {
val text = "Hello, World!"
println("Length of text in words: ${text.lengthInWords}") // Prints: Length of text in words: 6
}In this example, we created an extension property lengthInWords for the String type. It calculates the number of words in the string by dividing the string length by 3 (assuming each word contains 3 characters on average).
Extension functions are useful for several reasons:
What is the receiver type in the following example?
That's it for this lesson! With these concepts, you're well on your way to mastering Kotlin extension functions. Keep practicing, and happy coding! ✅
For more advanced topics, be sure to check out other tutorials on CodeYourCraft.