Table of contents
1.
Introduction
2.
What is Reflection?
3.
JVM Dependencies
3.1.
Adding dependency in Maven:
3.2.
Adding dependency in Gradle:
3.2.1.
Using Groovy Style
3.2.2.
Using Kotlin Style
4.
Class References
5.
Function References
6.
Property References
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Kotlin Reflection

Author Vasu Bansal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will discuss the reflection library in Kotlin and see the related JVM dependencies to use this API. This blog discusses different types of references, for example, class references, function references, property references, etc. Kotlin treats functions and properties as first-class citizens, and reflection API is majorly related to using these.

What is Reflection?

Reflection is a combination of language and library capabilities that allow you to analyze a program at the runtime. Kotlin reflection is mainly used to utilize class properties, methods, and constructors at the runtime. In addition to the Java reflection API, Kotlin has its own set of reflection API, which is written in a simple, functional style. The standard Java Reflection constructs are generally accessible and compatible with Kotlin programs.

Kotlin reflections are available in: 

kotlin.reflect package

JVM Dependencies

The Kotlin compiler distribution on the JVM platform includes the runtime component required for running the reflection API as a separate artifact. This artifact necessary for using the features of reflection is known as kotlin-reflect.jar.

To use reflection in a Maven/Gradle project, add the dependency as shown below:

Adding dependency in Maven:

<dependencies>
  <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-reflect</artifactId>
  </dependency>
</dependencies>

Adding dependency in Gradle:

Using Groovy Style

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-reflect:1.6.10"
}

Using Kotlin Style

dependencies {
    implementation("org.jetbrains.kotlin:kotlin-reflect:1.6.10")
}

Note: If Maven/Gradle is not used for creating the project, the kotlin-reflect.jar file must be added to the project's classpath. The route is added by default in some IDE-created projects. You can use the -no-reflect compiler option in the command-line compiler and Ant to remove kotlin-reflect.jar from the classpath.

Class References

The class reference operator is used to obtain a reference for a statically known class at the runtime. The instances of a class can also be used to get a reference to a class. Such references are called bounded class references. When reference is obtained using instances of a class, the reference obtained matches the exact type to which the class instance belongs. This concept is essentially helpful in the case of inheritance. To read more about Kotlin Classes and Objects, refer to the blog Kotlin Classes and Objects on the Coding Ninjas website. 

The class literal syntax can be used to obtain a reference to a statically known Kotlin class. This is demonstrated as follows.

// Creating class references in Kotlin
val obj = DemoClass::class

Note: A Kotlin class reference differs from a Java class reference on the JVM platform. You can use the .java property on a KClass instance to get a Java class reference.

The following is an example program to demonstrate class references in Kotlin.

// Kotlin program to demonstrate class reference

class CodingNinjas{
    // Class variables
    var student_id: Int;
    var name: String;

    constructor(_student_id: Int = -1, _name: String = ""){
        student_id = _student_id;
        name = _name;
    }
}

fun main(){
    // Class reference 
    var ref = CodingNinjas::class;
    println("Example of Class reference: $ref");

    // Bounded Class reference
    var obj = CodingNinjas(194, "Ninja");
    println("Example of Bounded Class reference: ${obj::class}");
}

Output:

Example of Class reference: class CodingNinjas
Example of Bounded Class reference: class CodingNinjas

Function References

Every named function defined in Kotlin can be referenced using a functional reference. This is accomplished by using the:: operator before the function name. These functional references can subsequently be passed to other functions as parameters. In the case of overloaded functions, the type of the function can be either explicitly specified or inferred from the content.

Let us consider the following example to understand function references in Kotlin. 

fun isNonZero(num: Int) = num != 0

When a named function is declared, as shown above, it can be directly invoked as isNonZero(10). An alternate way to invoke this function is to use it as a function type value and pass it to another function using the :: operator.  

For example, in the program given below, we are passing the function isNonZero to another function named filter, and this function is, in turn, invoking the isNonZero function.

// Kotlin program to demonstrate function references
fun isNonZero(num: Int) = num != 0

fun main(){
    val num_list = listOf(100,-10,0,5,3,0,-7);

    println(num_list.filter(::isNonZero)); 
// This will print all the non zero numbers in the list named num_list
}

Output:

[100,-10,5,3,-7]

Property References

Using the :: operator, we can get a property reference like a function reference. The class name should also be supplied with the :: operator if the property belongs to a class. Property references allow us to get or change the value of a property using the get or set functions as property references allow properties to be considered as objects.

The following program demonstrates the use of property references in Kotlin. The expression ::company_name evaluates to KProperty<String> property type object. The .name property is used to get the property name, the get() function is used to get its value, and the set() function is used to set the value. It is important to note that values of variables declared using the keyword val cannot be changed using the set() function as these variables are immutable.

// Kotlin program to demonstrate property references

var company_name: String = "Coding Ninjas"

fun main(){
    println("Variable name: " + ::company_name.name)
    println("Value: " + ::company_name.get())
    ::company_name.set("Coding Ninjas India")
    println("Updated value: " + ::company_name.get())
}

Output:

Variable name: company_name
Value: Coding Ninjas
Updated value: Coding Ninjas India

FAQs

  1. What are constructor references in Kotlin?
    Constructor references are used to refer to a class constructor without even instantiating that class. References to constructors can be passed as arguments or assigned to a target variable of a suitable type.
     
  2. Is Kotlin class reference the same as a Java class reference?
    Kotlin class references are not the same as a Java class references on the JVM platform. Java class reference can be obtained using the .java property on a KClass instance.
     
  3. Why does the Kotlin compiler include the runtime component required for using the reflection features as a separate artifact?
    The runtime component for using the reflection features is included in the Kotlin compiler distribution as a separate package named kotlin-reflect.jar. This is done to keep the size of the runtime library down for apps that don't use reflection.

Key Takeaways

Cheers if you reached here!! The purpose of this blog was to introduce you to the reflection library in Kotlin and learn about its various constructs like class references, function references, and property references. To read about regular expressions in Kotlin, go ahead and read the blog Kotlin Regex on the Coding Ninjas website.

Yet there is never an end to the learning process, so check out our Android Development Course on the Coding Ninjas Website to learn everything you need to know about Android development and how to design the applications of the future. Until then, good luck!!

Live masterclass