0
0
KotlinConceptBeginner · 3 min read

What is open keyword in Kotlin: Explanation and Examples

In Kotlin, the 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.

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

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

fun main() {
    val myDog = Dog()
    myDog.sound()
}
Output
Bark
🎯

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 final by default in Kotlin.
  • open allows inheritance and overriding.
  • Use open to design flexible and extendable code.
  • Helps prevent accidental changes by requiring explicit permission.

Key Takeaways

The open keyword lets classes and functions be inherited or overridden.
Kotlin classes and members are final by default to keep code safe.
Use open only when you want to allow extension or customization.
Marking a class open enables others to build upon it.
Overriding functions requires both the base function and the override to be marked properly.