Kotlin使用子类型覆盖乐趣 [英] Kotlin override fun with subtype

查看:72
本文介绍了Kotlin使用子类型覆盖乐趣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在继承包含基本类型的方法/乐趣的接口时遇到麻烦,我想在实现它的类中将其重写为子类型.

Im having trouble inheriting an interface containing a method/fun of a base type, that i would like to override as a subtype in the class implementing it.

到目前为止,我已经有了界面

So far i have the interface

interface IModel {
    fun convert(dataModel: BaseDataModel)
}

以及实现它的类:

class SettingsModel: IModel {
    override fun convert(dataModel: BaseDataModel) {
        // Conversion of models here

    }
}

我也有SettingsDataModel,它是:

And i also have the SettingsDataModel which is:

class SettingsDataModel: BaseDataModel() {
}

我想要实现的是针对实现IModel的每个类/模型,能够获得特定的DataModel,例如:

What i'm trying to achieve is for every class/model implementing IModel, being able to get the specific DataModel, like:

class SettingsModel: IModel {
    override fun convert(dataModel: SettingsDataModel) {
        // Conversion of models here

    }
}

无需强制转换.我想我做不到,因为它修改了乐趣的签名,使其不是真正的替代.我尝试使用泛型和泛型约束,但是没有运气:

without needing to cast it. I guess i cant because it modifies the signature of the fun making it not a real override. I tried using generics and generic constraints but no luck:

interface IModel {
    fun <T :BaseDataModel>convert(dataModel: T)
}

,但不起作用.有什么解决办法吗?

but its not working. Any work around for this?

推荐答案

如何?

interface IModel<T : BaseDataModel> {
    fun convert(dataModel: T)
}

class SettingsModel: IModel<SettingsDataModel> {
    override fun convert(dataModel: SettingsDataModel) {
        // Conversion of models here

    }
}

这篇关于Kotlin使用子类型覆盖乐趣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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