What if you could write common code once and never repeat it again?
Why Interface with default implementations in Kotlin? - Purpose & Use Cases
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.
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.
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.
interface Animal {
fun sound()
}
class Dog : Animal {
override fun sound() {
println("Bark")
}
}
class Cat : Animal {
override fun sound() {
println("Meow")
}
}interface Animal {
fun sound() {
println("Some sound")
}
}
class Dog : Animal {
override fun sound() {
println("Bark")
}
}
class Cat : Animal {}You can create flexible and reusable code that is easier to maintain and extend.
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.
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.