接口的功能与Property的getter发生冲突

编程入门 行业动态 更新时间:2024-10-28 10:32:23
本文介绍了接口的功能与Property的getter发生冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

接口的函数名称有意与属性的getter名称发生冲突,但是由于意外的覆盖问题,编译器禁止使用它.可以指示编译器是故意的吗?

An interface's function name clashes with a property's getter name intentionally, but it's prohibited by the compiler because of accidental override problem. Is it possible to instruct the compiler this is intentional?

interface A { fun getFoo() } class B: A { val foo }

推荐答案

此功能似乎无法以任何方式实现.

This feature seems not to be implemented in any way.

@AndreyBreslav对的评论>相似的问题:

@AndreyBreslav's comment on a similar question:

您目前无法使用Kotlin属性覆盖Java方法.如果可以支持它会很好,但是我们不知道如何在混合层次结构中始终如一地做到这一点

You can not override Java methods with Kotlin properties at the moment. It would be nice if we could support it, but we don't know how to do it consistently for mixed hierarchies

这不能解决您的问题,但至少可以使代码编译:您可以使用 @JvmName批注:

This does not solve your problem but at least makes the code compile: you can change JVM name of the getter with the @JvmName annotation:

interface A { fun getFoo(): SomeType } class B: A { override fun getFoo() = foo val foo: SomeType = someValue() @JvmName("getFoo_") get() = field }

此外,考虑更改为更惯用的方法:在界面中定义val -property,以便您可以在实现中覆盖它:

Also, consider changing to a more idiomatic approach: define the val-property in your interface, so that you can override it in the implementations:

interface A { val foo: SomeType } class B : A { override val foo: SomeType = someValue() } class C : A { override val foo: SomeType get() = someCustomGetter() }

更多推荐

接口的功能与Property的getter发生冲突

本文发布于:2023-10-22 09:24:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1517112.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:发生冲突   接口   功能   Property   getter

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!