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.

Each week I am looking at “items” from Joshua Bloch’s well-respected book, Effective Java to see how it applies to Kotlin. You can find the rest of the items I’ve covered at Effective Kotlin. Please let me know your thoughts.

Matt Dolan has been eating doughnuts and developing with Android since the dark days of v1.6.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store