nsL
nsL

Reputation: 3792

Kotlin override fun with subtype

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?

Upvotes: 5

Views: 4763

Answers (2)

s1m0nw1
s1m0nw1

Reputation: 81929

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.

Upvotes: 2

fal
fal

Reputation: 3075

How about this?

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

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

    }
}

Upvotes: 8

Related Questions