ProgrammingKotlin Developer

What is the difference between declaring a class with the 'open' keyword and a regular class in Kotlin, and how is inheritance implemented? Provide nuances, features, and a code example.

Pass interviews with Hintsage AI assistant

Answer

By default, all classes, methods, and properties in Kotlin are final. This means they cannot be inherited or overridden unless the open modifier is explicitly specified.

The open keyword allows inheritance of a class or overriding of a method. This is a fundamental difference from Java, where classes are open for inheritance by default.

Example:

open class Animal { open fun sayHello() { println("Hello from Animal!") } } class Dog : Animal() { override fun sayHello() { println("Woof!") } }
  • If you remove open from the Animal class, an attempt to inherit it will lead to a compilation error.
  • override is mandatory for methods/properties you want to override.
  • Interfaces are implemented using the interface keyword and do not require open.

Trick Question

In Kotlin, can you inherit any class just like in Java?

Answer: No, only classes marked as open (or abstract). Regular classes are final and cannot be inherited. This is done for increased safety and predictability of the code.

Example of incorrect code:

class Animal class Dog : Animal() // Compilation error: "Animal" is final

Examples of real errors due to misunderstanding the nuances of the topic


Story

In an Android platform project, a young developer tried to inherit a custom component from a custom View class but forgot to add open. The build failed, the reason was not obvious, and the deadlines shifted. The problem was only discovered after carefully reading the compiler message.


Story

While developing an SDK, the specification required an extensible base class, but it was declared without open. After delivery to clients, it turned out that the library could not be extended without modifying the source code. An update had to be released.


Story

In one project, old Java code was migrated to Kotlin without considering the default closure of classes. A large portion of unit tests that used mocks stopped compiling, delaying the release process. The problem was only resolved after mass addition of open.