1

I have an interface in Kotlin that I want to have default implementations so that implementing classes will only have to implement a subset of the methods. Example:

interface PersonInterface {
    val firstname: String?
        get() = null
    val lastName: String?
        get() =  null

    val phoneNumbers: List<String>?
        get() = null

    val interests: List<List<String>>?
        get() = emptyList()

}

This in my understanding would create default implementations for the methods to return null or an empty list or whatever I would have as defaults in general.
But if I create the following class in Java (which I expected it would compile):

public class Employee implements PersonInterface {
}

I get:

Class Employee must either be declared abstract or implement abstract method getFirstName in PersonInterface

Is it possible to use default interface implementation defined in Kotlin from Java?

1 Answer 1

3

According to documentation (https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html):

Starting from JDK 1.8, interfaces in Java can contain default methods. To make all non-abstract members of Kotlin interfaces default for the Java classes implementing them, compile the Kotlin code with the -Xjvm-default=all compiler option

Note: Prior to Kotlin 1.4, to generate default methods, you could use the @JvmDefault annotation on these methods. Compiling with -Xjvm-default=all in 1.4 generally works as if you annotated all non-abstract methods of interfaces with @JvmDefaultand compiled with -Xjvm-default=enable. However, there are cases when their behavior differs. Detailed information about the changes in default methods generation in Kotlin 1.4 is provided in this post on the Kotlin blog.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.