Reflection is a set of language and library features that provides the feature of introspecting a given program at runtime. Kotlin reflection is used to utilize class and its members like properties, functions, constructors, etc. at runtime.
Along with Java reflection API, Kotlin also provides its own set of reflection API’s, in a simple, functional style. The standard Java Reflection constructs are also available in Kotlin and work perfectly with its code.
Kotlin reflections are available in:
Features of Kotlin reflection –
- It gives access to properties and nullable types
- Kotlin reflection has some additional features to Java reflection.
- kotlin reflection helps in accessing the JVM code, written by a language
Class references –
To obtain a class reference at runtime which is statically known, use the class reference operator. Also, the reference to a class can also be obtained from the instances of the class, such references are known as bounded class references. Using instances, you obtain the reference to the exact type to which the object conforms to, in case of inheritance.
Example to demonstrate Class references
This is a class reference class kotlin1.com.programmingKotlin.chapter1.ReflectionDemo This is a bounded class reference class kotlin1.com.programmingKotlin.chapter1.ReflectionDemo
Function references –
We can obtain a functional reference to every named function that is defined in Kotlin. This can be done by preceding the function name with the :: operator. These functional references can then be used as parameters to other functions. In the case of overloaded functions, we can either explicitly specify the type of the function or it can be implicitly determined from the content.
Example to demonstrate Functional References
[3, 6, 9] fun add(kotlin.String, kotlin.String): kotlin.String 8
Property References –
We can obtain property reference in a similar fashion as that of function, using the :: operator. If the property belongs to a class then the class-name should also be specified with the :: operator. These property references allow us to treat a property as an object that is, we can obtain their values using get function or modify it using set function.
Example to demonstrate Property References
10 x 5.899
Constructor References –
The references to constructors of a class can be obtained in a similar manner as the references for methods and properties. These references can be used as references to a function which returns an object of that type. However, these uses are rare.
Example to demonstrate Constructor References