Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:
How to Get the Name of a Variable in Kotlin
Last updated: March 4, 2024
1. Overview
Kotlin has solid support for reflection, with functions and property names treated as first-class citizens. This makes it easy to introspect them. In this tutorial, we’ll specifically go over how to get the name of certain variables in Kotlin.
2. Name of a Class Property
KProperty<T> is an interface that represents a property, such as a named val or var declaration. KProperty is obtainable using the :: operator and has a name property that lets us get the property’s name. We’ll use this below to get the name of a class’s property:
class MyClass(val age: Int, var name: String, val next: MyClass?)
Assertions.assertEquals("next", MyClass::next.name)
In this case, we simply reference the class’s property through its enclosing class name, which gives us a KProperty to work with, and then access its name field.
We can also get the name from a class’s instance in a similar manner:
class MyClass(val age: Int, var name: String, val next: MyClass?)
val instance = MyClass(5, "test", null)
Assertions.assertEquals("next", instance::next.name)
3. Name of a Function
Let’s use the same approach to get the name of a function:
fun isValid(num: Int, name: String): Boolean = num > 0 && name.isNotBlank()
Assertions.assertEquals("isValid", ::isValid.name)
In this case, we used the :: operator but on a function to get its name. This time, the value was obtained through the KFunction interface.
4. Conclusion
In this short article, we went through how to get the name of a class property and a function in Kotlin using its powerful reflection APIs. We leveraged KProperty and KFunction to access their names via the :: operator. As of this writing, Kotlin doesn’t yet support getting the name of a local variable.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.