界面的功能与Property的getter冲突
一个接口的函数名与属性的getter名有意冲突,但由于意外覆盖问题,它被编译器禁止。 是否有可能指示编译器这是故意的?
interface A { fun getFoo() } class B: A { val foo }
这个功能似乎没有以任何方式实现。
@ AndreyBreslav对类似问题的评论:
您目前无法用Kotlin属性覆盖Java方法。 如果我们能够支持它,那将是非常好的,但是我们不知道如何对混合层次结构进行一致的处理
这并不能解决你的问题,但至少可以编译代码:你可以用@JvmName
注解来改变getter的JVM名称:
interface A { fun getFoo(): SomeType } class B: A { override fun getFoo() = foo val foo: SomeType = someValue() @JvmName("getFoo_") get() = field }
另外,考虑改用更习惯的方法:在界面中定义val
-property,以便在实现中覆盖它:
interface A { val foo: SomeType } class B : A { override val foo: SomeType = someValue() } class C : A { override val foo: SomeType get() = someCustomGetter() }