liveBook · Manning

KCallable

As explained in Kotlin in Action, 2E

KCallable is a Kotlin reflection superinterface for callable functions and properties, including operations for invoking them.

KCallable is the Kotlin reflection superinterface shared by functions and properties. Its generic call method invokes a reflected function or a property's getter with runtime arguments. section 12.2.1

Calling a reflected function

fun foo(x: Int) = println(x) val kFunction = ::foo kFunction.call(42) // 42 The ::foo reference produces a KFunction, which implements KCallable. call accepts arguments through vararg, so an incorrect argument count causes a runtime IllegalArgumentException. section 12.2.1

Choose the more specific callable interface when the function signature is known:

  • KFunction1<Int, Unit> exposes one parameter and a Unit return type; invoke accepts exactly one Int, and the function reference can also be called directly. section 12.2.1
  • KCallable.call provides a generic reflective path, while KFunction interfaces provide fixed-arity invoke operations with parameter and return-type information. section 12.2.1
  • KCallable.callBy can invoke methods while supplying default parameter values. section 12.3

Properties are callable too

var counter = 0 val kProperty = ::counter kProperty.setter.call(21) println(kProperty.get()) // 21 A reflected mutable property exposes getter and setter operations. Member properties can likewise retrieve a value by receiving the object, as in Person::age.get(person). section 12.3

KFunction and KProperty extend KCallable, while arity-specific function and property interfaces add typed invocation or value access. This hierarchy lets reflection enumerate declarations and invoke them dynamically at runtime. section 12.3

How Kotlin in Action, 2E covers it

How deep it goes
Explains the generic call operation, typed invoke variants, property access, mutation, and default-argument callBy support.
Examples
Uses function references, typed sums, a mutable counter, and a Person.age member property.
What you can do after
Apply it via Kotlin reflection to invoke functions and retrieve or change property values dynamically.
How it connects
Connects KCallable with Kotlin reflection, KClass, KFunction, KProperty, typed function interfaces, and mutable property interfaces.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.