Kotlin 1.4.32 Help

Kotlin/JS reflection

Kotlin/JS provides a limited support for the Kotlin reflection API. The only supported parts of the API are:

Class references

The ::class syntax returns a reference to the class of an instance, or the class corresponding to the given type. In Kotlin/JS, the value of a ::class expression is a stripped-down KClass implementation that supports only:

In addition to that, you can use KClass.js to access the JsClass instance corresponding to the class. The JsClass instance itself is a reference to the constructor function. This can be used to interoperate with JS functions that expect a reference to a constructor.

KType and typeOf()

The typeof() function constructs an instance of KType for a given type. To use typeOf() in your code, opt in to the experimental API of the standard library, for example, add @OptIn(ExperimentalStdlibApi::class) to your code.

The KType API is fully supported in Kotlin/JS except for Java-specific parts.


Here is an example of the reflection usage in Kotlin/JS.

open class Shape class Rectangle : Shape() @OptIn(ExperimentalStdlibApi::class) // typeOf() is experimental and requires an opt-in inline fun <reified T> accessReifiedTypeArg() = println(typeOf<T>().toString()) fun main() { val s = Shape() val r = Rectangle() println(r::class.simpleName) // Prints "Rectangle" println(Shape::class.simpleName) // Prints "Shape" println(Shape::class.js.name) // Prints "Shape" println(Shape::class.isInstance(r)) // Prints "true" println(Rectangle::class.isInstance(s)) // Prints "false" val rShape = Shape::class.cast(r) // Casts a Rectangle "r" to Shape accessReifiedTypeArg<Rectangle>() // Accesses the type via typeOf(). Prints "Rectangle" }
Last modified: 11 February 2021