I have below method in a companion object, which s...
# getting-started
p
I have below method in a companion object, which should extract a specific implementation class Wrapper depending on the Kotlin primitive type.
Copy code
fun extractRealClass(valueClass: Class<*>): Class<out PrimitiveWrapper<*>>? {

    return when (valueClass) {
        
        Boolean::class.java -> BooleanWrapper::class.java
        
        Int::class.java -> IntWrapper::class.java

        String::class.java -> StringWrapper::class.java

        else -> null
        
    }

}

// where PrimitiveWrapper is defined as:

open class PrimitiveWrapper<T>(val value: T) {... Above func lives in this class companion}

class BooleanWrapper(value: Boolean) : PrimitiveWrapper<Boolean>(value) { ... }

class IntWrapper(value: Int) : PrimitiveWrapper<Int>(value) { ... }
on another class
Entry
I have this:
Copy code
Entry<T: Any?>(
    private val key: String,
    private val clazz: Class<T>
) {

override fun getInstance(): T? {

    // It always return null when calling above mentioned func.
    val primitiveClass: Class<out PrimitiveWrapper<*>>?
                = PrimitiveWrapper.extractRealClass(clazz)

}

}
Whenever I call the
PrimitiveWrapper.extractClass(clazz)
with the save class info it always return null. I tried many things and no matter what in the
when
block the coming class always print like
int
or
<http://kotlin.Int|kotlin.Int>
but never
java.lang.Integer
. Could some body shed some light?
y
Hey! So, Its because Java primitive wrappers are not objects (nor Kotlin non nullable types are). So it will always show
int
or
<http://kotlin.Int|kotlin.Int>
(without '?') but never
java.lang.Integer
. Try it with a nullable
<http://kotlin.Int|kotlin.Int>?
and you may get
java.lang.Integer
p
Interesting, thanks. I will check that.
👍 1