简体   繁体   中英

How to infer a generic type in kotlin

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

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>?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM