5

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?

nsL
  • 3,722
  • 3
  • 23
  • 40
  • Side note: you can't restrain function params (because then someone who uses a interface's implementation couldn't use it) but you can be more specific about your return type (e.g.: in interface return is `Any` but you can in impl do `Int`) – Mibac Sep 07 '17 at 20:21

2 Answers2

5

How about this?

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

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

    }
}
fal
  • 2,997
  • 1
  • 22
  • 13
2

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.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196