Default implementation for Kotlin interfaces

In Kotlin, providing an implementation for an interface is very straightforward. There is no default keyword needed (which it is in Java). Instead, providing the implementation directly:

interface Processor {
    fun process() = println("default")

class KotlinProcessor : Processor {
    override fun process() = println("kotlin")

However, when implementing this Processor method from Java, it won’t inherit the default implementation at this moment. This is described in KT-4779.

As a workaround, you can either implement the interface in Java, or (since Kotlin 1.2.40) annotate the interface methods with the @JvmDefault annotation. This feature is experimental and therefore disabled by default. If you want to enable this, you’ll need to pass the -Xjvm-default=enable flag to the compiler for it to work.

Leave a Reply

Your email address will not be published. Required fields are marked *