Effective Kotlin: Item 19 — Design and document for inheritance or else prohibit it
Kotlin makes a bold move by making all classes
final by default, prohibiting inheritance unless explicitly requested using the
open keyword. Sitting nicely in line with Joshua Bloch’s recommendation in Effective Java, it requires more thought by the developer should they wish to create a class appropriate for inheritance. After all, favour composition over inheritance.
Of course, there are times when having
final classes can be frustrating, not least when you use frameworks such as Spring. But rather than “fix” the errors by making your classes
open there are better tools you can use. For example, the all-open compiler plugin helps by making classes annotated with a specific annotation and their members open without the explicit
open keyword. With Mockito the testing framework you can mock the un-mockable with an opt-in incubating feature.
Joshua talks a lot about adding appropriate documentation when you are designing a class for inheritance and although
open forms part of that documentation you still need to explain how a class works to help an implementor.
On the surface, KDoc, Kotlin’s equivalent of Java’s Javadoc, has a rather basic syntax. However, it’s worth highlighting that it supports Markdown out of the box so although it may not have built-in support for @implSpec introduced in Java 8 you can generate similar style documentation just as readily. The dokka tool is used to produce the documentation output.