0
0
Kotlinprogramming~3 mins

Why Interface with default implementations in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write common code once and never repeat it again?

The Scenario

Imagine you have many classes that need to share some common behavior, but each class also has its own unique parts. Without interfaces with default implementations, you would have to write the same code again and again in every class.

The Problem

Writing the same code repeatedly is slow and boring. It's easy to make mistakes or forget to update all copies when you want to change something. This wastes time and causes bugs.

The Solution

Interfaces with default implementations let you write shared code once inside the interface. Classes can then use this code automatically, only adding what's unique. This saves time and keeps code clean and consistent.

Before vs After
Before
interface Animal {
    fun sound()
}

class Dog : Animal {
    override fun sound() {
        println("Bark")
    }
}

class Cat : Animal {
    override fun sound() {
        println("Meow")
    }
}
After
interface Animal {
    fun sound() {
        println("Some sound")
    }
}

class Dog : Animal {
    override fun sound() {
        println("Bark")
    }
}

class Cat : Animal {}
What It Enables

You can create flexible and reusable code that is easier to maintain and extend.

Real Life Example

Think of a music app where many instruments can play sounds. The interface can provide a default way to play a sound, but each instrument can customize it if needed.

Key Takeaways

Writing shared code once inside interfaces saves time.

Classes can use default behavior or provide their own.

This leads to cleaner, easier-to-maintain code.