Welcome to the exciting world of Kotlin programming! Today, we're going to explore two powerful features: Extensions and Inheritance. Let's dive in!
Inheritance is a concept in object-oriented programming where one class (the subclass or child class) acquires the properties and methods of another class (the superclass or parent class). This allows us to reuse code and create more organized, modular programs.
Here's a simple example:
// Parent Class
open class Animal {
open fun makeSound() {
println("The animal makes a sound")
}
}
// Child Class
class Dog : Animal() {
override fun makeSound() {
println("Woof! Woof!")
}
}In this example, Dog is a subclass of Animal. It inherits the makeSound() method from the Animal class, but we've overridden it to make the Dog bark.
Extensions, on the other hand, allow us to add new functions to existing classes without inheriting from them or modifying the original source code. This can be incredibly useful when you want to expand the functionality of a third-party library or a final class that can't be subclassed.
Here's an example:
// Extension function for String
fun String.reverse(): String {
return this.reversed()
}
fun main() {
val text = "Hello, World!"
println(text.reverse()) // Prints: !dlroW ,olleH
}In this example, we've created an extension function reverse() for the String class. Now, we can call this function on any String instance, like we did with text.
So, when should you use extensions and when should you use inheritance?
What is the purpose of the `open` keyword in Kotlin?
What does the `reverse()` extension function do?