Support KClass.isInstance/cast/safeCast in stdlib-only reflection implementation

#KT-14720 Fixed
This commit is contained in:
Alexander Udalov
2019-10-24 19:37:29 +02:00
parent 5c89f2fa54
commit 896512f7cd
10 changed files with 80 additions and 42 deletions
@@ -0,0 +1,40 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
@file:kotlin.jvm.JvmName("KClasses")
@file:Suppress("UNCHECKED_CAST")
package kotlin.reflect
/**
* Casts the given [value] to the class represented by this [KClass] object.
* Throws an exception if the value is `null` or if it is not an instance of this class.
*
* This is an experimental function that behaves as a similar function from kotlin.reflect.full on JVM.
*
* @see [KClass.isInstance]
* @see [KClass.safeCast]
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
fun <T : Any> KClass<T>.cast(value: Any?): T {
if (!isInstance(value)) throw ClassCastException("Value cannot be cast to $qualifiedName")
return value as T
}
/**
* Casts the given [value] to the class represented by this [KClass] object.
* Returns `null` if the value is `null` or if it is not an instance of this class.
*
* This is an experimental function that behaves as a similar function from kotlin.reflect.full on JVM.
*
* @see [KClass.isInstance]
* @see [KClass.cast]
*/
@SinceKotlin("1.3")
@ExperimentalStdlibApi
fun <T : Any> KClass<T>.safeCast(value: Any?): T? {
return if (isInstance(value)) value as T else null
}