``` val Class<*>.boxed get() = if (isPrim...
# stdlib
m
Copy code
val Class<*>.boxed
	get() =
		if (isPrimitive)
			when (this) {
				Boolean::class.java -> java.lang.Boolean::class.java
				Char::class.java -> java.lang.Character::class.java
				Byte::class.java -> java.lang.Byte::class.java
				Short::class.java -> java.lang.Short::class.java
				Int::class.java -> java.lang.Integer::class.java
				Long::class.java -> java.lang.Long::class.java
				Float::class.java -> java.lang.Float::class.java
				Double::class.java -> java.lang.Double::class.java
				Void.TYPE -> java.lang.Void::class.java
				else -> error("Unexpected primitive class: $this")
			}
		else
			this


fun Class<*>.isAssignableOrBoxableTo(otherClass: Class<*>) =
	otherClass.isAssignableOrBoxableFrom(this)


fun Class<*>.isAssignableOrBoxableFrom(otherClass: Class<*>) =
	boxed.isAssignableFrom(otherClass.boxed)
🤔 Would that be useful for stdlib?
e
But what is the use-case? Why would one need this? In what kind of code / cases?
m
I’m writing a JSON encoder/decoder. One encoder declared that it can encode
Boolean::class.java
but it encountered a
java.lang.Boolean::class.java
which was not reported as assignable (using
Class.isAssignableFrom
) and thus the encoder wasn’t used, although it could’ve been.
I wouldn’t expect anyone writing an encoder that they cannot use
Boolean::class.java
because it refers to the primitive type (there isn’t a distinction in Kotlin). So it should work just fine, which it does with the code above.
i
Take a look at
javaPrimitiveType/javaObjectType
extensions functions on
KClass
, probably you can use them instead of
boxed
m
Nice one, thanks! Why does it use string comparison though? Doesn’t that hurt performance? Also, doesn’t work for `void`:
java.lang.Void.TYPE.kotlin
->
Copy code
exception: java.lang.AssertionError: Non-primitive type name passed: void
	at kotlin.reflect.jvm.internal.impl.resolve.jvm.JvmPrimitiveType.get(JvmPrimitiveType.java:60)
	at kotlin.reflect.jvm.internal.RuntimeTypeMapper.getPrimitiveType(RuntimeTypeMapper.kt:279)
	at kotlin.reflect.jvm.internal.RuntimeTypeMapper.mapJvmClassToKotlinClassId(RuntimeTypeMapper.kt:266)
	at kotlin.reflect.jvm.internal.KClassImpl.getClassId(KClassImpl.kt:176)
	at kotlin.reflect.jvm.internal.KClassImpl.toString(KClassImpl.kt:271)
reported the error: https://youtrack.jetbrains.com/issue/KT-20875 😄