I have a Kotlin interface with a default implementation, for instance:
interface Foo { fun bar(): String { return "baz" } }
This would be okay until I try to implement this interface from Java. When I do, it says the class need to be marked as abstract or implement the method bar()
. Also when I try to implement the method, I am unable to call super.bar()
.
Unlike earlier version of Java8, Kotlin can have default implementation in interface.
Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store a state. They can have properties, but these need to be abstract or provide accessor implementations.
In Kotlin, a class can implement multiple interfaces. This is common knowledge. A class can also use delegation to implement numerous interfaces where the implementations come from any delegated objects passed into the constructor.
As mentioned earlier, Kotlin doesn't support multiple inheritances, however, the same thing can be achieved by implementing more than two interfaces at a time.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With