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 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.

As always, you can find the code samples over on GitHub.


« 上一篇: 在MockK中使用Spy
» 下一篇: Kotlin 修改map值操作