Home > Enterprise >  Type mismatch: why there is .Companion?
Type mismatch: why there is .Companion?

Time:12-17

I wrote the following function:

fun <T> myFunction(res: Response, type: T): T {
        return res.`as`(type!!::class.java)
}

And I would like to use it in the following way:

fun anotherFunction(): MyClass {
        val res = getResponse()
        return myFunction(res, MyClass)
}

But I get the following error:

Type mismatch.

Required: MyClass

Found: MyClass.Companion

How can I solve it?

CodePudding user response:

I don't know exactly what the as function does, but I suppose it performs some sort of conversion from one class instance into an instance of some other class?

You seem to be trying to pass a class type as a function argument. You can do it in one of two ways:

fun <T: Any> myFunction(res: Response, type: Class<T>): T {
    return res.`as`(type)
}

fun anotherFunction(): MyClass {
    val res = getResponse()
    return myFunction(res, MyClass::class.java)
}

or

inline fun <reified T: Any> myFunction(res: Response): T {
    return res.`as`(T::class.java)
}

fun anotherFunction(): MyClass {
    val res = getResponse()
    return myFunction(res) // <MyClass> is inferred by anotherFunction return type
}
  • Related