Using the default function for an interface in Kotlin

I have a Kotlin interface with a default implementation, for example:

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

This will be fine until I try to implement this interface with Java. When I do this, he says that the class should be marked as abstract or implement the method bar(). Also, when I try to implement a method, I cannot call super.bar().

+16
source share
3 answers

Please see the related issue .

There is a recommendation in the comments:

Write your interface in Java (with default methods), and the Java and Kotlin classes use these default values ​​correctly

+8
source

default Java, Kotlin 1.2.40.

@JvmDefault @JvmDefault:

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

- , -Xjvm-default=enable . ( Gradle, ).

, . , , , , , IDE Java - - , , , .

+11

Java8, Kotlin .

Foo Java. Kotlin . .

Java, /. Kotlin , Java-.

, ( , Java8).

.

, , .

Kotlin binaries were compiled using java-bytecode version 1.8 without standard methods in the interfaces. And they are faced with a decisive problem that solves it.

0
source

Source: https://habr.com/ru/post/1677910/


All Articles