我试图在Kotlin中基于java数组实现检查 。但是我将KClass与允许空值的通用参数类型一起使用时遇到问题。Stack<E><E>
Java泛型类型在运行时不可用,但数组类型可用。我想使用此功能,以便在运行时进行内置类型检查。
有关已检查/未检查的更多详细信息,可以在这里找到/sf/answers/37120261/
interface Stack<E> {
fun push(elem: E)
fun pop(): E
}
Run Code Online (Sandbox Code Playgroud)
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 …Run Code Online (Sandbox Code Playgroud)