Polymorphism in Kotlin

Polymorphism is a core concept of object-oriented programming that allows objects to be treated as instances of their parent class rather than their actual class. It enables one interface to be used for multiple forms (types) of objects.

1. Why Polymorphism Matters

2. Types of Polymorphism in Kotlin

Polymorphism in Kotlin can be broadly classified into:

3. Compile-time Polymorphism (Method Overloading)


class Calculator {
    fun add(a: Int, b: Int) = a + b
    fun add(a: Int, b: Int, c: Int) = a + b + c
}

fun main() {
val calc = Calculator()
println(calc.add(2, 3))       // Output: 5
println(calc.add(2, 3, 4))    // Output: 9
} 

4. Runtime Polymorphism (Method Overriding)


open class Animal {
    open fun sound() {
        println("Some generic sound")
    }
}

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

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

fun main() {
val animals: List = listOf(Dog(), Cat())
for (animal in animals) {
animal.sound()  // Runtime decides which sound() to call
}
} 

Output:


Bark
Meow
  

5. Polymorphism with Interfaces


interface Flyer {
    fun fly()
}

class Bird : Flyer {
override fun fly() = println("Bird is flying")
}

class Plane : Flyer {
override fun fly() = println("Plane is flying")
}

fun main() {
val flyers: List = listOf(Bird(), Plane())
flyers.forEach { it.fly() }
} 

Output:


Bird is flying
Plane is flying
  

6. Technical Interview Questions

7. Key Takeaways