通过使用具有在超类中定义的相同名称的var来覆盖接口中定义的val [英] Overriding val defined in interface by using var with the same name defined in superclass

查看:89
本文介绍了通过使用具有在超类中定义的相同名称的var来覆盖接口中定义的val的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Base 类( var 需要保持受保护):

There is a Base class (var needs to stay protected):

open class Base(protected var id: Int) {}

有一个界面需要使用 val

interface ProviderI {
    val id: Int
}

还有一个继承自 <的类em> Base 并实现 ProviderI 界面。我正在尝试使用超类 var (具有相同名称)来实现接口的 val
作为一个不起作用的例子,我正在尝试做类似的事情(例子不起作用):

There is also a class which inherits from Base and implements the ProviderI interface. Within which I'm trying to implement the interface's val using the superclass var (which has the same name). As a not working example, I'm trying to do something like that (example does not work):

class Instance(id: Int): Base(id), ProviderI {
    override val id
        get() { return super.id }
}

这个想法很简单,但我已经尝试了所有内容,并且每次报告不同的错误。

The idea is simple but I've tried everything and every time different error is reported.

推荐答案

要覆盖多个超类型中存在的成员,Kotlin要求所有超类型中的打开 ,这个限制看起来很自然,因为否则 final 成员可以通过这种方式轻松覆盖。

To override a member that is present in several supertypes, Kotlin requires it to be open in all supertypes, and this restriction looks quite natural, because otherwise final members could be easily overridden in this way.

解决方案是在 Base 中打开 id 并将其覆盖为 var property:

The solution is to make id open in Base as well and to override it as a var property:

open class Base(protected open var id: Int)

interface ProviderI {
    val id: Int
}

class Instance(id: Int): Base(id), ProviderI {
    override var id: Int
        get() = super.id
        set(value) { super.id = value }
}

这篇关于通过使用具有在超类中定义的相同名称的var来覆盖接口中定义的val的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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