Kotlin icon

Though Kotlin and Spring Boot play well together, there are some friction areas between the two. IMHO, chief among them is the fact that Kotlin classes and methods are final by default.

The Kotlin docs cite the following reason:

The open annotation on a class is the opposite of Java’s final: it allows others to inherit from this class. By default, all classes in Kotlin are final, which corresponds to Effective Java, Item 17: Design and document for inheritance or else prohibit it.

Kotlin designers took this advice very seriously by making all classes final by default. In order to make a class (respectively a method) inheritable (resp. overridable), it has to be annotated with the open keyword. That’s unfortunate because a lot of existing Java libraries require classes and methods to be non-final. In the Spring framework, those mainly include @Configuration classes and @Bean methods but there also Mockito and countless other frameworks and libs. All have in common to use the cglib library to generate a child class of the referenced class. Ergo: final implies no cglib implies no Spring, Mockito, etc.

That means one has to remember to annotate every required class/method. This is not only rather tedious, but also quite error-prone. As an example, the following is the message received when one forgets about the annotation on a Spring configuration class:

org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem:
@Configuration class 'KotlindemoApplication' may not be final. Remove the final modifier to continue.

Here’ what happens when the @Bean method is not made open:

org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem:
@Bean method 'controller' must not be private or final; change the method's modifiers to continue

The good thing is that the rule are quite straightforward: if a class is annotated with @Configuration or a method with @Bean, they should be marked open as well. From Kotlin 1.0.6, there’s a compiler plugin to automate this process, available in Maven (and in Gradle as well) through a compiler plugin’s dependency. Here’s the full configuration snippet:

{% highlight xml linenos %}

kotlin-maven-plugin org.jetbrains.kotlin ${kotlin.version} all-open org.jetbrains.kotlin kotlin-maven-allopen ${kotlin.version} compile compile compile test-compile test-compile test-compile

{% endhighlight %}

Note on lines 10-11 the list of all annotations for which the open keyword is now not mandatory anymore.

Even better, there’s an alternative plugin dedicated to Spring projects, that makes listing Spring-specific annotations not necessary. Lines 6-13 above can be replaced with the following for a shorter configuration:


Whether using Spring, Mockito or any cglib-based framework/lib, the all-open plugin is a great way to streamline the development with the Kotlin language.