Reputation: 5348
Consider I'm trying to implement delegation by storing properties in a Map
instance, and one of the properties delegated is an array:
class Foo private constructor(map: Map<String, Any?>) {
constructor(value: Array<Byte>) : this(mapOf(Foo::value.name to value))
val value: Array<Byte> by map
}
object PropertyDelegationTest {
@JvmStatic
fun main(vararg args: String) {
val foo = Foo(arrayOf(42.toByte(), 127.toByte()))
println(foo.value[0]) // 42
println(foo.value[1]) // 127
}
}
The above compiles just fine and works as expected.
Now consider I want to enhance my property delegation mechanism by implementing a custom Map.getValue(thisRef: Any?, property: KProperty<*>)
extension method (overriding the default extension):
import kotlin.reflect.KProperty
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.starProjectedType
import kotlin.reflect.jvm.jvmName
// ...
operator fun <V, V1 : V> Map<in String, V>.getValue(thisRef: Any?, property: KProperty<*>): V1 {
val value = this[property.name]
?: throw NoSuchElementException("Key ${property.name} is missing in the map.")
val clazz = (value as Any)::class
@Suppress("UNCHECKED_CAST")
return when {
clazz.starProjectedType.isSubtypeOf(property.returnType) -> value as V1
else -> throw ClassCastException("${clazz.starProjectedType} (${clazz.jvmName}) cannot be cast to ${property.returnType}")
}
}
This fails at run time:
Exception in thread "main" java.lang.ClassCastException: kotlin.Array<*> ([Ljava.lang.Byte;) cannot be cast to kotlin.Array<kotlin.Byte>
at com.example.PropertyDelegationTestKt.getValue(PropertyDelegationTest.kt:30)
at com.example.Foo.getValue(PropertyDelegationTest.kt)
at com.example.PropertyDelegationTest.main(PropertyDelegationTest.kt:18)
Despite the effective JVM type is known ([Ljava.lang.Byte;
), Kotlin-specific run time type of the value is Array<*>
while Array<Byte>
is required. Consistently, clazz.typeParameters[0].upperBounds[0]
evaluates to kotlin.Any?
, not kotlin.Byte?
.
How do I implement my custom type checking which would also work correctly for arrays? Kotlin version is 1.2.71.
Upvotes: 1
Views: 230
Reputation: 7036
You could remove the explicit type check and instead do a safe cast to V1
and if that fails then throw the exception, e.g.
return value as? V1 ?: throw ClassCastException(...
Upvotes: 1