Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using default function implementation of interface in Kotlin

Tags:

kotlin

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().

like image 590
Vojtěch Avatar asked May 25 '17 11:05

Vojtěch


People also ask

Can a function implement an interface Kotlin?

Unlike earlier version of Java8, Kotlin can have default implementation in interface.

How do you implement interfaces in Kotlin?

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.

Can you implement multiple interfaces in Kotlin?

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.

How many interfaces can a class implement Kotlin?

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.


1 Answers

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.

like image 175
zsmb13 Avatar answered Sep 22 '22 22:09

zsmb13