Reflection

Reflection allows us to introspect code at runtime; this is implemented by a set of languages and standard library features. The Kotlin standard library contains the kotlin.reflect package that, in turn, contains classes that represent references to elements, such as classes, functions, or properties.

To obtain a reference to an element, we should use the :: operator. The following example demonstrates how to obtain a reference to a class:

val reference: KClass<String> = String::class

As you can see, references to classes are represented by the KClass class.

References to functions can also be passed to high-order functions. The following example shows how this may look:

fun isOdd(number: Int): Boolean = number % 2 == 0
val odds = listOf(1, 2, 3, 4, 5).filter(::isOdd)

A reference to a property is represented by the KProperty class, and this can be obtained in the following way:

val referenceToOddsPreperty = ::odds

KProperty is a class that represents a property of a class, and it can be used to retrieve metadata, such as names or types.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.220.22