Search code examples
genericsinheritancekotlinkotlin-generics

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?


Solution

  • How about this?

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