Reflection

Reflection is a set of language and library features that allows for introspecting the structure of your own program at runtime. Kotlin makes functions and properties first-class citizens in the language, and introspecting them (i.e. learning a name or a type of a property or function at runtime) is closely intertwined with simply using a functional or reactive style.

On the JavaScript platform, only class references are currently supported. Learn more about reflection in Kotlin/JS.

JVM dependency

On the JVM platform, the runtime component required for using the reflection features is distributed as a separate artifact kotlin-reflect.jar in the Kotlin compiler distribution. 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:

  • In Gradle:

    1. dependencies {
    2. implementation "org.jetbrains.kotlin:kotlin-reflect:1.4.21"
    3. }
    1. dependencies {
    2. implementation("org.jetbrains.kotlin:kotlin-reflect:1.4.21")
    3. }
    • In Maven:
    1. <dependencies>
    2. <dependency>
    3. <groupId>org.jetbrains.kotlin</groupId>
    4. <artifactId>kotlin-reflect</artifactId>
    5. </dependency>
    6. </dependencies>

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, using command-line compiler or Ant), it is added by default. In command-line compiler and Ant, you can use -no-reflect compiler option to exclude kotlin-reflect.jar from the classpath.

Class references

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:

  1. val c = MyClass::class

The reference is a value of type KClass.

Note that a Kotlin class reference is not the same as a Java class reference. To obtain a Java class reference, use the .java property on a KClass instance.

Bound class references (since 1.1)

You can get the reference to a class of a specific object with the same ::class syntax by using the object as a receiver:

  1. val widget: Widget = ...
  2. assert(widget is GoodWidget) { "Bad widget: ${widget::class.qualifiedName}" }

You obtain the reference to an exact class of an object, for instance GoodWidget or BadWidget, despite the type of the receiver expression (Widget).

Callable references

References to functions, properties, and constructors, apart from introspecting the program structure, 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, which is the property type for properties, and the constructed type for constructors.

Function references

When we have a named function declared like this:

  1. fun isOdd(x: Int) = x % 2 != 0

We can easily call it directly (isOdd(5)), but we can also use it as a function type value, e.g. pass it to another function. To do this, we use the :: operator:

  1. fun isOdd(x: Int) = x % 2 != 0
  2. fun main() {
  3. //sampleStart
  4. val numbers = listOf(1, 2, 3)
  5. println(numbers.filter(::isOdd))
  6. //sampleEnd
  7. }

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, e.g. KFunction3<T1, T2, T3, R>.

:: can be used with overloaded functions when the expected type is known from the context. For example:

  1. fun main() {
  2. //sampleStart
  3. fun isOdd(x: Int) = x % 2 != 0
  4. fun isOdd(s: String) = s == "brillig" || s == "slithy" || s == "tove"
  5. val numbers = listOf(1, 2, 3)
  6. println(numbers.filter(::isOdd)) // refers to isOdd(x: Int)
  7. //sampleEnd
  8. }

Alternatively, you can provide the necessary context by storing the method reference in a variable with an explicitly specified type:

  1. val predicate: (String) -> Boolean = ::isOdd // refers to isOdd(x: String)

If we need to use a member of a class, or an extension function, it needs to be qualified, e.g. String::toCharArray.

Note that even if you initialize a variable with a reference to an extension function, the inferred function type will have no receiver (it will have an additional parameter accepting a receiver object). To have a function type with receiver instead, specify the type explicitly:

  1. val isEmptyStringList: List<String>.() -> Boolean = List<String>::isEmpty

Example: function composition

Consider the following function:

  1. fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
  2. return { x -> f(g(x)) }
  3. }

It returns a composition of two functions passed to it: compose(f, g) = f(g(*)). Now, you can apply it to callable references:

  1. fun <A, B, C> compose(f: (B) -> C, g: (A) -> B): (A) -> C {
  2. return { x -> f(g(x)) }
  3. }
  4. fun isOdd(x: Int) = x % 2 != 0
  5. fun main() {
  6. //sampleStart
  7. fun length(s: String) = s.length
  8. val oddLength = compose(::isOdd, ::length)
  9. val strings = listOf("a", "ab", "abc")
  10. println(strings.filter(oddLength))
  11. //sampleEnd
  12. }

Property references

To access properties as first-class objects in Kotlin, we can also use the :: operator:

  1. val x = 1
  2. fun main() {
  3. println(::x.get())
  4. println(::x.name)
  5. }

The expression ::x evaluates to a property object of type KProperty<Int>, which allows us to read its value using get() or retrieve the property name using the name property. For more information, please refer to the docs on the KProperty class.

For a mutable property, e.g. var y = 1, ::y returns a value of type KMutableProperty<Int>, which has a set() method:

  1. var y = 1
  2. fun main() {
  3. ::y.set(2)
  4. println(y)
  5. }

A property reference can be used where a function with a single generic parameter is expected:

  1. fun main() {
  2. //sampleStart
  3. val strs = listOf("a", "bc", "def")
  4. println(strs.map(String::length))
  5. //sampleEnd
  6. }

To access a property that is a member of a class, we qualify it:

  1. fun main() {
  2. //sampleStart
  3. class A(val p: Int)
  4. val prop = A::p
  5. println(prop.get(A(1)))
  6. //sampleEnd
  7. }

For an extension property:

  1. val String.lastChar: Char
  2. get() = this[length - 1]
  3. fun main() {
  4. println(String::lastChar.get("abc"))
  5. }

Interoperability with Java reflection

On the JVM platform, 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 say something like this:

  1. import kotlin.reflect.jvm.*
  2. class A(val p: Int)
  3. fun main() {
  4. println(A::p.javaGetter) // prints "public final int A.getP()"
  5. println(A::p.javaField) // prints "private final int A.p"
  6. }

To get the Kotlin class corresponding to a Java class, use the .kotlin extension property:

  1. fun getKClass(o: Any): KClass<Any> = o.javaClass.kotlin

Constructor references

Constructors can be referenced just like methods and properties. They can be used wherever an object of function type is expected 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:

  1. class Foo
  2. fun function(factory: () -> Foo) {
  3. val x: Foo = factory()
  4. }

Using ::Foo, the zero-argument constructor of the class Foo, we can simply call it like this:

  1. function(::Foo)

Callable references to constructors are typed as one of the KFunction<out R> subtypes , depending on the parameter count.

Bound function and property references (since 1.1)

You can refer to an instance method of a particular object:

  1. fun main() {
  2. //sampleStart
  3. val numberRegex = "\\d+".toRegex()
  4. println(numberRegex.matches("29"))
  5. val isNumber = numberRegex::matches
  6. println(isNumber("29"))
  7. //sampleEnd
  8. }

Instead of calling the method matches directly we are storing a reference to it. Such reference is bound to its receiver. It can be called directly (like in the example above) or used whenever an expression of function type is expected:

  1. fun main() {
  2. //sampleStart
  3. val numberRegex = "\\d+".toRegex()
  4. val strings = listOf("abc", "124", "a70")
  5. println(strings.filter(numberRegex::matches))
  6. //sampleEnd
  7. }

Compare the types of bound and the corresponding unbound references. Bound callable reference has its receiver “attached” to it, so the type of the receiver is no longer a parameter:

  1. val isNumber: (CharSequence) -> Boolean = numberRegex::matches
  2. val matches: (Regex, CharSequence) -> Boolean = Regex::matches

Property reference can be bound as well:

  1. fun main() {
  2. //sampleStart
  3. val prop = "abc"::length
  4. println(prop.get())
  5. //sampleEnd
  6. }

Since Kotlin 1.2, explicitly specifying this as the receiver is not necessary: 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:

  1. class Outer {
  2. inner class Inner
  3. }
  4. val o = Outer()
  5. val boundInnerCtor = o::Inner