What is open keyword in Kotlin: Explanation and Examples
open keyword allows a class or a member (like a function or property) to be inherited or overridden. By default, classes and their members are final and cannot be extended unless marked with open.How It Works
Imagine you have a toy that you can only play with as it is, without changing its parts. In Kotlin, classes and their functions are like that toy by default—they are final, meaning you cannot change or extend them. The open keyword is like giving permission to modify or add new parts to the toy.
When you mark a class or a function with open, you tell Kotlin that it is okay for other classes to inherit from it or override its behavior. This is useful when you want to create a base class that others can build upon or customize.
Example
This example shows a base class marked with open and a subclass that overrides a function.
open class Animal { open fun sound() { println("Some sound") } } class Dog : Animal() { override fun sound() { println("Bark") } } fun main() { val myDog = Dog() myDog.sound() }
When to Use
Use the open keyword when you want to allow other developers or parts of your program to extend your classes or change how certain functions work. For example, if you are creating a library or framework, marking classes as open lets users customize behavior by inheritance.
Without open, Kotlin prevents accidental changes and helps keep your code safe and predictable. So, only use open when you really want to allow extension or modification.
Key Points
- Classes and members are
finalby default in Kotlin. openallows inheritance and overriding.- Use
opento design flexible and extendable code. - Helps prevent accidental changes by requiring explicit permission.
Key Takeaways
open keyword lets classes and functions be inherited or overridden.open only when you want to allow extension or customization.open enables others to build upon it.