接口的功能与Property的getter发生冲突 [英] Interface's function clashes with Property's getter

查看:58
本文介绍了接口的功能与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


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


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发生冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆