Reflection is a set of language and library features that allows you to introspect the structure of your program at runtime. Functions and properties are first-class citizens in Kotlin, and the ability to introspect them (for example, learning the name or the type of a property or function at runtime) is essential when using a functional or reactive style.
On the JVM platform, the Kotlin compiler distribution includes the runtime component required for using the reflection features as a separate artifact, kotlin-reflect.jar . This is done to reduce the required size of the runtime library for applications that do not use reflection features.
To use reflection in a Gradle or Maven project, add the dependency on kotlin-reflect :
If you don't use Gradle or Maven, make sure you have kotlin-reflect.jar in the classpath of your project. In other supported cases (IntelliJ IDEA projects that use the command-line compiler or Ant), it is added by default. In the command-line compiler and Ant, you can use the -no-reflect compiler option to exclude kotlin-reflect.jar from the classpath.
The most basic reflection feature is getting the runtime reference to a Kotlin class. To obtain the reference to a statically known Kotlin class, you can use the class literal syntax:
The reference is a KClass type value.
Bound class references
You can get the reference to the class of a specific object with the same ::class syntax by using the object as a receiver:
You will obtain the reference to the exact class of an object, for example, GoodWidget or BadWidget , regardless of the type of the receiver expression ( Widget ).
References to functions, properties, and constructors can also be called or used as instances of function types .
The common supertype for all callable references is KCallable<out R> , where R is the return value type. It is the property type for properties, and the constructed type for constructors.
When you have a named function declared as below, you can call it directly ( isOdd(5) ):
Alternatively, you can use the function as a function type value, that is, pass it to another function. To do so, use the :: operator:
Here ::isOdd is a value of function type (Int) -> Boolean .
Function references belong to one of the KFunction<out R> subtypes, depending on the parameter count. For instance, KFunction3<T1, T2, T3, R> .
:: can be used with overloaded functions when the expected type is known from the context. For example:
Alternatively, you can provide the necessary context by storing the method reference in a variable with an explicitly specified type:
If you need to use a member of a class or an extension function, it needs to be qualified: String::toCharArray .
Even if you initialize a variable with a reference to an extension function, the inferred function type will have no receiver, but it will have an additional parameter accepting a receiver object. To have a function type with a receiver instead, specify the type explicitly:
Example: function composition
Consider the following function:
It returns a composition of two functions passed to it: compose(f, g) = f(g(*)) . You can apply this function to callable references:
To access properties as first-class objects in Kotlin, use the :: operator:
The expression ::x evaluates to a KProperty0<Int> type property object. You can read its value using get() or retrieve the property name using the name property. For more information, see the docs on the KProperty class .
For a mutable property such as var y = 1 , ::y returns a value with the KMutableProperty0<Int> type which has a set() method:
A property reference can be used where a function with a single generic parameter is expected:
To access a property that is a member of a class, qualify it as follows:
For an extension property:
Interoperability with Java reflection
On the JVM platform, the standard library contains extensions for reflection classes that provide a mapping to and from Java reflection objects (see package kotlin.reflect.jvm ). For example, to find a backing field or a Java method that serves as a getter for a Kotlin property, you can write something like this:
To get the Kotlin class that corresponds to a Java class, use the .kotlin extension property:
Constructors can be referenced just like methods and properties. You can use them wherever the program expects a function type object that takes the same parameters as the constructor and returns an object of the appropriate type. Constructors are referenced by using the :: operator and adding the class name. Consider the following function that expects a function parameter with no parameters and return type Foo :
Using ::Foo , the zero-argument constructor of the class Foo , you can call it like this:
Callable references to constructors are typed as one of the KFunction<out R> subtypes depending on the parameter count.
Bound function and property references
You can refer to an instance method of a particular object:
Instead of calling the method matches directly, the example uses a reference to it. Such a reference is bound to its receiver. It can be called directly (like in the example above) or used whenever a function type expression is expected:
Compare the types of the bound and the unbound references. The bound callable reference has its receiver "attached" to it, so the type of the receiver is no longer a parameter:
A property reference can be bound as well:
You don't need to specify this as the receiver: this::foo and ::foo are equivalent.
Bound constructor references
A bound callable reference to a constructor of an inner class can be obtained by providing an instance of the outer class:
Software developer vs software engineer: know the differences, software development projects, the ultimate guide to top front end and back end programming languages for 2021, software development methodologies: everything you need to know, serialization in java, type casting in java: everything you need to know, 20 most popular programming languages to learn in 2023, list to string in python, free coding class: learn how to build a food delivery app like ubereats, top 40 coding interview questions you should know, here’s all you need to know about kotlin reflection.
Table of Contents
The ability to examine, load, and interact with classes, fields, and methods at runtime is referred to as Kotlin reflection. In this article on Kotlin reflection, we will be learning about various topics of Kotlin reflection in detail.
What is Kotlin Reflection?
In Kotlin, Reflection is a combination of language and library capabilities that allow you to introspect a program while it's running. Kotlin reflection is used at runtime to utilize a class and its members, such as properties, methods, and constructors. It is also used to create instances of classes, inspect annotations, lookup functions, and invoke them.
Kotlin features its own reflection API, which is built in a clean, functional style, in addition to the Java reflection API.
Now, let us understand some features of the Kotlin reflection.
Here's How to Land a Top Software Developer Job
Features of Kotlin Reflection
- It provides access to properties and nullable types that aren't available in Java.
- Kotlin Reflection includes a few extra features over Java reflection.
- Kotlin reflection aids in gaining access to JVM code written by a language.
Now that we've understood the features of Kotlin reflection, let's go ahead and understand Kotlin class references.
Kotlin Class References
At runtime, the class reference operator is used to get a reference to a statically known class. A class's instances can also be utilized to obtain a reference to a class. Bounded class references are the name for these types of references. When employing instances of a class to obtain a reference, the reference obtained corresponds to the type to which the instance of the class belongs. In the case of inheritance, this concept is extremely useful.
Let us take a look at this example.
Here xyz is the object, Reflection is the name of the class that we are using with class literal, and using the class reference operator, we are obtaining the class reference.
After that, using the object or instance of the class, we obtain the reference to the class, and that reference is known as a bounded class reference.
Below is the output of the above code.
Next is Kotlin Function references.
Basics to Advanced - Learn It All!
Kotlin Function References
Every named function defined in Kotlin can be referenced via a functional reference. To do so, use the:: operator before the function name. provided as parameters to other functions. In the case of overloaded functions, the function type might be provided explicitly or inferred from the text.
Here in the example, We're sending the Negative function to another function called filter, which in turn is calling the Negative function.
On printing the above program, all the negative values will get printed.
Now, moving on to Kotlin property references.
Kotlin Property References
With the help of the :: operator, we can get a property reference in the same way we get a function reference. The class name should also be mentioned with the :: operator if the property belongs to a class. Because property references allow properties to be considered objects, we can use the get and set functions to get or alter the value of a property.
Let’s have a look at an example.
As we can see in this example, the expression ::variable allows you to retrieve its property; by using name, it prints the name; by using get it prints its value, and using set method, it updates the value of the property.
Kotlin Constructor References
The references to a class' constructors are obtained in the same way that the references to methods and properties are obtained. These references can be used to indicate a function that returns a type-specific object.
The :: operator is used to refer to constructors, followed by the class name. Using ::Sub, we can easily call the sub constructor.
Looking to accelerate your career as a skilled Full Stack Web Developer? Leverage Caltech CTME's academic excellence in a unique bootcamp-style Post Graduate Program in Full Stack Web Development . Enroll Now!
In this tutorial on Kotlin reflection, you understood what is a Kotlin reflection and learned various topics, including Kotlin class references and function references. You learned about the Features of Kotlin reflection, Kotlin property references, and constructor references with the help of examples.
If you are looking to build a software development career, you can check the Post-Graduate Program in Full Stack Web Development by Simplilearn. It can be the ideal solution to help you build your career in the right direction.
Do you have any questions about this Kotlin reflection tutorial? If you do, then you can put them in the comments section. We’ll help you solve your queries at the earliest.
Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:
About the author.
Harsh is a Research Analyst at Simplilearn. He has a good hand at C++, Java, CSS, SQL, and a good grasp of Kotlin language. Harsh is quite interested in traveling, spirituality, and playing football.
Post Graduate Program in Full Stack Web Development
Full Stack Web Developer - MEAN Stack
Full Stack Java Developer Job Guarantee Program
*Lifetime access to high-quality, self-paced e-learning content.
The Ultimate Guide to Kotlin Constructors With Examples
A Simple and Ultimate Guide to Kotlin Flows
The Perfect Guide to Understand a Kotlin Data Class
C# Reflection to Aid Us in Discovering the Metadata of Your Code
Kotlin Null Safety
All You Need to Know About Kotlin Delegation
The Best Article Out There What Is Kotlin
- PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.
- Android Studio
- Kotlin Android
- Android Projects
- Android Interview Questions
- Write an Interview Experience
- Share Your Campus Experience
- Kotlin Tutorial
- Introduction to Kotlin
- Kotlin Environment setup for Command Line
- Kotlin Environment setup with Intellij IDEA
- Hello World program in Kotlin
- Kotlin Data Types
- Kotlin Variables
- Kotlin Operators
- Kotlin Standard Input/Output
- Kotlin Type Conversion
- Kotlin Expression, Statement and Block
- Kotlin if-else expression
- Kotlin while loop
- Kotlin do-while loop
- Kotlin for loop
- Kotlin when expression
- Kotlin Unlabelled break
- Kotlin labelled continue
Array & String
- Kotlin Array
- Kotlin String
- Kotlin functions
- Kotlin | Default and Named argument
- Kotlin Recursion
- Kotlin Tail Recursion
- Kotlin | Lambdas Expressions and Anonymous Functions
- Kotlin Inline Functions
- Kotlin infix function notation
- Kotlin Higher-Order Functions
- Kotlin Collections
- Kotlin list : Arraylist
- Kotlin list : listOf()
- Kotlin Set : setOf()
- Kotlin hashSetOf()
- Kotlin Map : mapOf()
- Kotlin Hashmap
- Kotlin Class and Objects
- Kotlin Nested class and Inner class
- Kotlin Setters and Getters
- Kotlin | Class Properties and Custom Accessors
- Kotlin constructor
- Kotlin Visibility Modifiers
- Kotlin Inheritance
- Kotlin Interfaces
- Kotlin Data Classes
- Kotlin Sealed Classes
- Kotlin Abstract class
- Enum Classes in Kotlin
- Kotlin extension function
- Kotlin generics
- Kotlin Exception Handling | try, catch, throw and finally
- Kotlin Nested try block and multiple catch block
- Kotlin Null Safety
- Kotlin | Type Checking and Smart Casting
- Kotlin | Explicit type casting
Regex & Ranges
- Kotlin Regular Expression
- Kotlin Ranges
- Java Interoperability – Calling Kotlin from Java
- Java Interoperability – Calling Java from Kotlin
- Kotlin annotations
- Kotlin Operator Overloading
- Destructuring Declarations in Kotlin
- Equality evaluation in Kotlin
- Comparator in Kotlin
- Triple in Kotlin
- Pair in Kotlin
- Kotlin | apply vs with
- Kotlin for Android Tutorial
- How to create project in Android Studio using Kotlin
- How to Install Android Virtual Device(AVD)?
- Android Animations in Kotlin
- Android Fade In/Out in Kotlin
- Android Menus
- Android progress notifications in Kotlin
- Android Project folder Structure
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
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
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
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
Please Login to comment...
Improve your coding skills with practice.
Understanding Reflection using Kotlin
Almost all frameworks or libraries utilize the power of reflection under the hood. knowing about it would make you a better developer..
Level Up Coding
Have you ever wondered how the libraries or frameworks, that rely on the JVM-based languages such as Kotlin or Java, work under the hood? To me, it had been some sort of black magic unless I came across the idea of reflection. In libraries like Retrofit or Kotlin-serialization, you define a bunch of classes or interfaces and annotate them with some predefined keywords and it works perfectly in the runtime. The same is true for Android. You extend some classes such as Main-Activity or ViewModel and the end result is a functioning app.
However, it is really not obvious that how do these libraries know what you defined or exactly where you did that. There must be some mechanism built into these languages that allow playing with the statically defined classes and interfaces at runtime. This is precisely what reflection is built for.
In this article, I would attempt to demystify reflection through a few trivial code examples. I understand that you are not always supposed to dig into the details of a library. It is crucial for a developer to be able to appreciate abstraction. Although, getting a high-level glimpse of how these frameworks function under the hood would, of course, augment your development toolbox.
Who knows you might be building a bleeding-edge framework, that solves many problems of those that are in existence right now, in the upcoming years or so.
Disclaimer: Keep in your mind that most frameworks or libraries will not always be using reflection for everything. Since reflection is a slower process as compared to the other primitive programming stuff the frameworks would implement intermediate compilers.
What is reflection?
In a nutshell, reflection enables you to reference statically defined classes, functions, or interfaces at runtime. Post that you can introspect it. You may,
- Access the properties or functions of the class irrespective of the access-modifier
- Find out whether any member of that class has been annotated with some particular annotations
- Manipulate the class/interface as necessary
That is an immense power. As I have mentioned you can even manipulate the private properties of a class. So, yeah, you have to be scrupulous while using reflection as it breaks encapsulation.
Before using reflection in your Kotlin project you have to add the following dependency to your build.gradle file.
Reflection in action
We will begin by defining a dummy class that would let you taste reflection.
We can, now, instantiate the class itself either from the class name or from the object of that class.
As shown in the code snippet, there is two way to grab the reference of the class. We can either user className::class or objectReference::class .
To obtain the Java equivalent class you may use the className/objectReference::class.java syntax.
While these are almost the same, there are subtle differences between the types that these varying syntaxes would produce.
Why the designers of the language have decided to use two different types, i.e KClass<T> and KClass<out T> or Class<T> and Class<out T> , is beyond the scope of this article.
If you are familiar with Kotlin’s way of expressing type-variance in generics you may have already understood that the interfaces which have <out T> are actually implemented with declaration-site variance. If you have no idea what type-variance actually is you may later check out this enlightening illustrated guide on Kotlin’s type variance . However, you need not worry much about type-variance right now. You don’t need to learn it to understand reflection.
Accessing the member functions
It is time that we do something with the class reference. Let’s start with something simple — print the name of all the member functions of that class.
The memberFunctions property returns a list of all the member functions of a given class. If you are wondering where do the methods, that we haven’t explicitly declared, namely equals hashCode and toString , came from here is the explanation. These three methods are declared in Kotlin’s Any class which all other classes — by default — inherit from unless stated otherwise.
Invoking the member functions
This is how we can invoke the member functions using the KClass<out Dummy> variable.
The only thing to notice here is whenever we want to invoke a function using a reference that is of KFunction<*> type we need to pass an object that is an instantiation of the corresponding class while using the call function. The reason is straightforward, a class is just a blueprint it cannot behave independently. Hence, an object is needed.
Invoking a private function
Up until now, we have only worked with public functions from that class. However, as I have mentioned that private functions and property can also be accessed here is an example of it.
To access a private function there is an extra step. We need to explicitly set the isAccessible property of that KFunction<*> variable as true . Failing to do that would inevitably welcome an IllegalAccessException at runtime.
Accessing properties (private)
Here is how you can access the properties of the class.
As you can see the process is really similar to the previous demonstrations. Just like the private functions, it is necessary to explicitly make private properties accessible. The type of the properties, in this case, i.e KProperty1<out Dummy, *> , is a bit cumbersome. Although, you need not worry about it too much if you could not grasp it right away. The KProperty type has a couple of variants designed for different properties. You may learn more in the Kotlin API reference for KProperty .
Manipulating property values
To manipulate the values of the properties we need to cast the property into the KMutableProperty type.
In the shown code-snippet we have modified the value of the property before the getter actually accessed it. Thus the output is different.
A Brief Summary
- Reflection enables us to introspect or manipulate the behavior of a class or interface at runtime.
- Using reflection we can even access the properties and functions marked with the private access-modifier.
- Reflection is heavily utilized in a library or framework.
- It can be found whether any class or its members were marked with some predefined annotations so that a library or framework can act accordingly.
- Reflection is not a very fast process. Therefore, heavy frameworks or libraries seldom implement intermediate compilers.
- Reflection gives us enormous power. So, utmost care must be taken while using it.
We will be wrapping up here for today. Hopefully, you have gained a basic level of understanding of reflection. You also have a general idea about what goes on under the hood while our code uses a framework or library.
Although, well will not simply end our quest here. In the next article, we will be building a simple annotation processor. We would define our very own annotations. The end result will be a dummy string parser that would encode/decode JSON data. Annotation and reflection go hand in hand. So, I would urge you to stay tuned for the next one.
Thank you so much for making it thus far. I would really appreciate a couple of words on your thought ✏️.
You can support my work by buying me a cup of coffee . ☕
Nilanjan 🌱🌱 is writing programming-related articles
Hey 👋 i write programming-related articles. i am still a student. you can make my day by buying me a coffee..
Written by Nilanjan 🌱🌱
More from nilanjan 🌱🌱 and level up coding.
How to Access Database with Kotlin using JDBC: The Fundamentals
Learn how databases are accessed at the low-level using jdbc.
I Spent 30 Days Studying A Programmer Who Built a $230 Billion Company After Quitting His 9–5 —…
Steal this programmer blueprint.
Python Libraries for Lazy Data Scientists
Do you feel lethargic today use these five libraries to boost your productivity..
Sealed Class vs Enum in Kotlin
Whats the difference between sealed class and enum.
Data Structures in Kotlin: Array — [PartI]
Hey everyone in this article series, we’ll be exploring data structures and their implementations in kotlin. we’ll explore different….
Apple's Vision Pro
It's never too late or early to start something
Interview Hacking Ninja
Kotlin Interview Questions (41–60)
What are object expressions in kotlin and when to use them.
Retrofit Or Ktor ?????
Question we (android developers) are asking from ourselves…..
Hello, today’s post will be about kotlin collections. i was having a problem for 2 days in my application that i developed, and the problem….
The Single Responsibility of an Android Activity
Last month i did a talk “cleaner code by delegation” at the androidheads vienna monthly meetup. one of the key takeaways was the importance….
Text to speech
- Interview Q
Control flow, exception handling, null safety, collections, annotations, kotlin oops, java interoperability, android startup, kotlin android.
- Send your Feedback to [email protected]
Help Others, Please Share
Learn Latest Tutorials
Python Design Patterns
B.Tech / MCA
JavaTpoint offers too many high quality services. Mail us on h [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] . Duration: 1 week to 2 week
Kotlin Reflection Recipes
Kotlin Reflection has poor documentation so I decided to gather together all code samples that I used when I wrote my library. I hope this article will help you to save time.
This article contains a collection of recipes for Kotlin Reflection. You can find and play with all samples from the article in my Github repository .
Original reflection types
Read these articles before proceeding:
- Official documentation about reflection
- Reflection with Kotlin article
KClass and a KType are two originals classes where Kotlin reflection begins.
KClass represents a class. It contains information about a class name, constructors, members, and so on.
KType represents a type. It contains a KClass and a type argument for generics types.
Recipe 1 : How to get a KClass
Method 1: from a type, method 2: from an instance, method 3: from a ktype, recipe 2 : how to get a ktype, method 1: from a kclass, simple type, generic type with a type argument, generic type with the star type.
Unlike the previous example, here we lose all information about a type argument.
Method 2: From the typeOf<> method
The typeOf<>() method is experimental now. It will probably be stable in Kotlin 1.6 .
Generics type with a type argument
The typeOf<>() method supports generic types and returns correct type parameters information.
Method 3: From a constructor parameter
Method 4: from a member property.
There are other ways to get a KType I gave you only several examples to show the basic principles.
Recipe 4 : How to get a type argument from a generic type
A KClass doesn’t contain information about a type argument only a KType contains. So before getting the type argument you have to have the KType for your type.
Recipe 5 : Refined type parameters
- Official documentation about inline functions and refined type parameters .
- StackOverflow question about refined type parameters
Pass a KClass as an argument
Get a kclass from a refined parameter, get a kclass from an argument, recipe 6 : how to traverse a class.
A class for examination:
The code will print:
Declared Methods traverse
All methods traverse, a method call, nested classes traverse, class annotations traverse, field annotations traverse.
- Annotation use-site targets
- Stackoverflow question about annotations
Recipe 7 : How to create a class
Using a class constructor, array with parameters, named parameters, using a class name.
Kotlin has no method to create a KClass by name, so you have to use the Class.forName method from Java then convert obtained Class to the KClass . To be consistent, you have to use the class.java.name method from Java to get the class name instead of the class.qualifiedName method from Kotlin, because they return different names.
As you can see from the output Kotlin’s class.qualifiedName returns a different name than Java’s class.java.name .
- ← Previous Post
- Next Post →
Introduction to the reflection feature in Kotlin
by Nathan Sebhastian
Posted on Jan 27, 2022
In programming, reflection is a programming language’s ability to inspect and interact with statically defined classes, functions, and properties during runtime.
The feature is particularly useful when you receive an object instance of an unknown class.
By using reflection, you can check if a particular object has a certain method, and call that method when it exists.
To use reflection in Kotlin, you need to include the kotlin-reflect library in your project:
The library contains the runtime component required for using Kotlin reflection features.
Next, let’s see how you can get class, function, and property references using Kotlin reflection feature.
Kotlin reflection - class reference
Suppose you have a Dog class with the following definitions:
To get the class reference in Kotlin, you can use the class literal syntax ::class as shown below:
Alternatively, you can get the class reference from an object instance by using the same ::class syntax on the instance:
Getting the class reference from an object is also known as a bounded class reference .
Once you have the class reference, you can access the properties of the reference to find out more about that class.
For example, you can find the name of the class and check if that class is a data class:
In Kotlin, the class reference is identified as the Kclass type which stands for Kotlin class.
You can check the Kclass documentation for all properties and methods you can access to find out about the class from its reference.
Aside from inspecting the class, the Kclass also has some interesting abilities. The createInstance() method, for example, allows you to create a new object from the class reference:
But keep in mind that the createInstance() method only works when the class has a constructor with optional or no parameter.
An error will be thrown when no constructor fulfills the criteria.
Accessing Kotlin class reference methods
You can also get access to the methods of the class reference regardless of their access modifier.
This means even private functions of a class can be accessed from its reference.
The memberFunctions property of Kclass stores all methods of the class as a Collection :
The output will be as follows:
Next, you can call the class function from its reference as follows:
First, you need to use the find() function to retrieve the function reference.
Then, check if the function reference is found using the null-safe call.
When the reference is found, use the call() method from the function reference Kfunction type.
The first argument of the call() method must be an instance of the class reference, which is why myDog object is passed into the method.
When your function is private , you need to change the isAccessible property of the function reference as true first before calling the function:
And that’s how you access the methods of a class using its reference.
Accessing Kotlin class reference properties
The properties of a Kotlin class reference can be accessed the same way you access its methods.
The properties of a class are stored in memberProperties as a Collection .
For example, you can get the name property value of the myDog instance as follows:
A property reference is an instance of KProperty type. The value of the property is retrieved by calling the getter() method.
To change the value of the name property, you need to cast the property into KMutableProperty first as shown below:
The KMutableProperty holds the setter() method, which you need to call to set the value of the property.
Now you’ve learned how to access methods and properties from a class reference.
Next, let’s look at how you can get a function reference with Kotlin reflection
Kotlin reflection - function reference
You can get a reference to a named Kotlin function by using the :: operator.
Here’s an example:
The funRef above will be an instance of Kfunction type , which represents a function with introspection capabilities.
Now you’ve learned what the Kotlin reflection feature is and how it works with some examples. Reflection is a powerful feature that’s only used for specific requirements.
Because of its ability to find inspect a source code, it’s frequently used when developing a framework or library for further development.
JUnit and Spring frameworks are notable for using reflection in their source code.
The library author won’t know the classes and functions created by the user. Reflection allows the framework to deal with classes and functions without knowing about them in advance.
Take your skills to the next level ⚡️
I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!
Learn more about this website
Connect with me on Twitter
Type the keyword below and hit enter
Click to see all tutorials tagged with: