How to pass class parameter with Generics to function


#1

Hi there,

The following code generate a compiler Error:(6, 41) Kotlin: Type inference failed. Expected type mismatch: inferred type is Class<CmdEcho<*>> but Class<out CmdEcho> was expected

What is a proper way to pass CmdEcho to function call?

package com.cuma.kotlin

class TestG<X> {
    fun test(): CmdEcho<X> {
        val util = CmdUtil<CmdEcho<X>>()
        return util.call(CmdEcho::class.java)
    }
}

class CmdUtil<Y> {
    fun call(x: Class<out Y>): Y  {
        return x.newInstance()
    }
}

class CmdEcho<X> {
}

Thanks
Simon


#2

The code does not compile because CmdEcho::class.java does not specify any type parameter for CmdEcho; its type is CmdEcho<*> which does not match CmdEcho<X>. Here’s one possible way to fix this code:

class TestG<X> {
    fun test(): CmdEcho<X> {
        val util = CmdUtil<CmdEcho<*>>()
        return util.call(CmdEcho::class.java) as CmdEcho<X>
    }
}

class CmdUtil<Y> {
    fun call(x: Class<out Y>): Y  {
        return x.newInstance()
    }
}

class CmdEcho<X> {
}

How to pass Java class as parameter to Kotlin annotation?