I'm trying to implement checked Stack<E>
based on java array in Kotlin. But I have a problem with using KClass with my generic parameter type <E>
which allows null values.
Java Generic types are not available in runtime, but array types are available. I want to use this feature so that there is built-in type checking in runtime.
More details about the checked/unchecked can be found here https://stackoverflow.com/a/530289/10713249
interface Stack<E> {
fun push(elem: E)
fun pop(): E
}
class CheckedStack<E>(elementType: Class<E>, size: Int) : Stack<E> {
companion object {
inline fun <reified E> create(size: Int): CheckedStack<E> {
//**compile error here**
return CheckedStack(E::class.javaObjectType, size)
}
}
@Suppress("UNCHECKED_CAST")
private val array: Array<E?> = java.lang.reflect.Array.newInstance(elementType, size) as Array<E?>
private var index: Int = -1
override fun push(elem: E) {
check(index < array.size - 1)
array[++index] = elem
}
override fun pop(): E {
check(index >= 0);
@Suppress("UNCHECKED_CAST")
return array[index--] as E
}
}
I expect that this code will work like this:
fun main() {
val intStack = CheckedStack.create<Int>(12) // Stack must store only Integer.class values
intStack.push(1); //[1]
intStack.push(2); //[1, 2]
val stackOfAny: Stack<Any?> = intStack as Stack<Any?>;
stackOfAny.push("str") // There should be a runtime error
}
But I have the compile error
Error:(39, 42) Kotlin: Type parameter bound for T in val <T : Any> KClass<T>.javaObjectType: Class<T>
is not satisfied: inferred type E is not a subtype of Any
In order to fix it, I need to bound the type parameter <E : Any>
but I need the stack to be able to work with nullable values <T : Any?>
. How to fix it?
Why is KClass declared as KClass<T : Any>
not KClass<T : Any?>
?
UPD: It works if use E::class.java
instead E::class.javaObjectType
Because the property val <T> KClass<T>.java: Class<T>
has type param <T>
with annotation @Suppress("UPPER_BOUND_VIOLATED")
.
But the property val <T : Any> KClass<T>.javaObjectType: Class<T>
has type <T : Any>
.
In my case, Kotlin compiles Int to Integer.class rather than int (in my case). But I'm not sure that it will always work as well.