Kotlin override fun with subtype

4.2k Views Asked by At

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)
}

And the class implementing it:

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

    }
}

And i also have the SettingsDataModel which is:

class SettingsDataModel: BaseDataModel() {
}

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?

2

There are 2 best solutions below

0
fal On BEST ANSWER

How about this?

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

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

    }
}
0
s1m0nw1 On

I guess i cant because it modifies the signature of the fun making it not a real override

You're right, this is not possible: Kotlin, same as Java, does not allow covariant method arguments. Two methods fun foo(n: Number) and fun foo(I: Int) would be considered "overloads" instead of "overrides".

You should go use generics. See an example here.