Polymorphism is an object-oriented programming language concept. In Polymorphism, a single function can be used differently by modifying its argument count and types. Method overloading and overriding are both included in Polymorphism. By enabling Polymorphism in Kotlin, we can write flexible and reusable code.
Polymorphism in Kotlin: Comprehensive Guide with Examples
Types of Polymorphism in Kotlin:
There are 2 types of Polymorphism in Kotlin, Method overloading and Method Overriding.
1. Method Overloading:
In method overloading, we can define multiple functions in the same class with the same name but their parameters should be different. It is a compile-time polymorphism.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
class CustomMathUtils { fun add(a: Int, b: Int): Int { return a + b } fun add(a: Double, b: Double): Double { return a + b } fun add(){ println("Add function Called...") } } fun main() { val mathObject = CustomMathUtils() println("Sum of Integers: ${mathObject.add(5, 2)}") println("Sum of Doubles: ${mathObject.add(7.5, 12.5)}") mathObject.add() } // Output // Sum of Integers: 7 // Sum of Doubles: 20.0 // Add function Called... |
Code explanation: In this example, we have created a custom class and defined 3 add functions with the same name but their parameters are different. Two functions are different argument and different return type functions and one function is no argument no return type. So at the time of function calling based on our passing argument it calls the function.
2. Method Overriding:
In method overriding, we can override the whole function and its functionality. Method overriding is used with inheritance. If you don’t know about Inheritance, I have created a post explaining. In inheritance, we can inherit all class public functions and variables into another class. After inheritance, we can either override the function or use it directly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
open class CommonUtils { open fun showWelcomeMessage() { println("Welcome to our website!!") } } class Messages : CommonUtils() { override fun showWelcomeMessage() { println("Welcome Friends..!!") } } fun main() { val messageObject = Messages() messageObject.showWelcomeMessage() } // Output Welcome Friends..!! |
Code explanation: In this example, we have created an open class with an open function. Now we are enabling inheritance in the CommonUtils class into the Message class and overriding its function showWelcomeMessage().
Conclusion:
Understanding polymorphism in Kotlin can increase code efficacy and maintainability because it is one of the basic concepts of object-oriented programming languages.