How to pass class parameter with Generics to function

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> {
}
1 Like