Reflection: add KClass.{isSubclassOf,isSuperclassOf}, KType.{isSubtypeOf,isSupertypeOf}
The behavior in primitives.kt is likely to be reconsidered #KT-8998 Fixed
This commit is contained in:
@@ -223,3 +223,16 @@ val KClass<*>.allSuperclasses: Collection<KClass<*>>
|
||||
get() = allSupertypes.map { supertype ->
|
||||
supertype.classifier as? KClass<*> ?: throw KotlinReflectionInternalError("Supertype not a class: $supertype")
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` if `this` class is the same or is a (possibly indirect) subclass of [base], `false` otherwise.
|
||||
*/
|
||||
fun KClass<*>.isSubclassOf(base: KClass<*>): Boolean =
|
||||
this == base ||
|
||||
DFS.ifAny(listOf(this), KClass<*>::superclasses) { it == base }
|
||||
|
||||
/**
|
||||
* Returns `true` if `this` class is the same or is a (possibly indirect) superclass of [derived], `false` otherwise.
|
||||
*/
|
||||
fun KClass<*>.isSuperclassOf(derived: KClass<*>): Boolean =
|
||||
derived.isSubclassOf(this)
|
||||
|
||||
@@ -19,6 +19,7 @@ package kotlin.reflect
|
||||
|
||||
import org.jetbrains.kotlin.types.TypeUtils
|
||||
import org.jetbrains.kotlin.types.isFlexible
|
||||
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
|
||||
import kotlin.reflect.jvm.internal.KTypeImpl
|
||||
|
||||
/**
|
||||
@@ -35,3 +36,18 @@ fun KType.withNullability(nullable: Boolean): KType {
|
||||
|
||||
return if (!nullable) this else KTypeImpl(TypeUtils.makeNullable(kotlinType)) { javaType }
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Returns `true` if `this` type is the same or is a subtype of [other], `false` otherwise.
|
||||
*/
|
||||
fun KType.isSubtypeOf(other: KType): Boolean {
|
||||
return (this as KTypeImpl).type.isSubtypeOf((other as KTypeImpl).type)
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns `true` if `this` type is the same or is a supertype of [other], `false` otherwise.
|
||||
*/
|
||||
fun KType.isSupertypeOf(other: KType): Boolean {
|
||||
return other.isSubtypeOf(this)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user