Using default function implementation of interface in Kotlin

后端 未结 4 1687
没有蜡笔的小新
没有蜡笔的小新 2020-12-29 01:47

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

interface Foo {
    fun bar(): String {
        return \"baz\"
    }
}
4条回答
  •  佛祖请我去吃肉
    2020-12-29 02:12

    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.

提交回复
热议问题