Using default function implementation of interface in Kotlin

Generating true default methods callable from Java is an experimental feature of Kotlin 1.2.40.

You need to annotate the methods with the @JvmDefault annotation:

interface Foo {
    @JvmDefault
    fun bar(): String {
        return "baz"
    }
}

This feature is still disabled by default, you need to pass the -Xjvm-default=enable flag to the compiler for it to work. (If you need to do this in Gradle, see here).

It really is experimental, however. The blog post warns that both design and implementation may change in the future, and at least in my IDE, Java classes are still marked with errors for not implementing these methods, despite compiling and working fine.


Please see the related issue.

There is a recommendation in the comments:

Write your interface in Java (with default methods) and both the Java and Kotlin classes correctly use those defaults

Tags:

Kotlin