Home > Mobile >  How to infer a generic type in kotlin
How to infer a generic type in kotlin

Time:08-21

I've done this code and don't uderstand what could be wrong :

   fun <T : ComplicationDataSourceService> getCorrespondingComplicationService(): Class<T>? {
        return when (this) {
            IMMOBILITY -> ImmobilityComplicationService::class.java
            HEART_RATE -> null
            POWER_BUTTON -> null
            SHORTCUT -> null
        }
    }
class ImmobilityComplicationService: ComplicationDataSourceService() {
    ...
}

I got this compilation error : Type mismatch, required: Class<T>? Found: Class<ImmobilityComplicationService>

Thanks

CodePudding user response:

Your function signature claims that the caller can choose a T, and it'll return a Class<T> for that T, no matter what it is.

That's not true. Your function returns a Class for some subclass of ComplicationDataSourceService, but the caller doesn't pick that type.

Instead, the correct type of your function is

fun getCorrespondingComplicationService(): Class<out ComplicationDataSourceService>?
  • Related