Industrial Training




Kotlin Reflection


Reflection is a set of language and library features that examines the structure of program at runtime. Kotlin makes functions and properties as first-class citizen in the language and examine these functions and properties at runtime.


Class Reference


Class reference is used to obtain the reference of KClass object. To obtain the reference of statically Kclass, we should use the class literal(i.e. use double colons).


Syntax of class reference:
val c1 = String::class  
val c2 = MyClass::class  

The reference value is a class type of KClass. KClass class reference is not the same as a Java class reference. We obtain the Java class reference by using .java property on a KClass instance.


Note: KClass represents a class and provides examination capabilities. To obtain the instance of this class use syntax ::class.


Functional Reference


Kotlin functional is used to obtain the reference of function using double colons. The reference of function can be used in another function as a parameter. To use this reference in another function we use the :: operator:


fun isPositive(x: Int) = x> 0   

fun isPositive(x: Int) = x> 0  
val number = listOf(-10,-5,0,5,10)  
print(number.filter(::isPositive))  

Kotlin functional reference example


fun main(args: Array) {  
    fun isPositive(x: Int) = x > 0  
val numbers = listOf(-10, -5, 0, 5, 10)  
println(numbers.filter(::isPositive))   
}  

Output:
[5,10]

In the above program ::isPositive is a value of function type (Int) -> Boolean.


Overloaded function reference operator (::)


The operator :: can be used with overload function when the expected type is known from the context. For example:
Create a function isPositive() which takes two different types Int and String and call this function with different type parameter.


fun main(args: Array) {  
    fun isPositive(x: Int) = x > 0  
    fun isPositive(s: String) = s== "kotlin" || s == "Kotlin"  
  
val numbers = listOf(-10,-5,0,5,10)  
val strings = listOf("kotlin", "program")  
  
println(numbers.filter(::isPositive))  
println(strings.filter(::isPositive))  
}  

Output:
[5, 10]
[kotlin]

Property Reference


We can also access the properties as first-class object in Kotlin, to access object property we can use :: operator:
To evaluate the property object of type KProperty< Int> we use the expression ::variableName. The expression ::variableName allow to retrieve its property name by using name and readits value using get() function.
To reset the value of mutable type property, reference property has set() method.


fun main(args: Array) {  
println(::x.get())  
println(::x.name)  
println(::y.set(10))  
}  
val x = 5  
var y = 5  

Output:
5
x
10

Access the property of member class:


Property reference also access the property of other member of class. For example:


class A(val x: Int)  
fun main(args: Array) {  
val prop = A::x  
println(prop.get(A(5)))  
}  


Output:
5



Hi I am Pluto.