Kotlin Extensions vs Inheritance 🎯

beginner
11 min

Kotlin Extensions vs Inheritance 🎯

Welcome to the exciting world of Kotlin programming! Today, we're going to explore two powerful features: Extensions and Inheritance. Let's dive in!

Understanding Inheritance 📝

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:

kotlin
// 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.

Entering the Extension Realm 💡

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:

kotlin
// 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.

When to Use Extensions vs Inheritance ✅

So, when should you use extensions and when should you use inheritance?

  • Use inheritance when you want to create a new class that is a specialized version of an existing class, and you want to reuse its properties and methods.
  • Use extensions when you want to add new functionality to an existing class, but you don't want to or can't inherit from it.

Quiz Time 🎮

Quick Quiz
Question 1 of 1

What is the purpose of the `open` keyword in Kotlin?

Quick Quiz
Question 1 of 1

What does the `reverse()` extension function do?