liveBook · Manning

KFunction

As explained in Kotlin in Action, 2E

KFunction is the Kotlin reflection interface representing a function declaration or callable function value.

KFunction is Kotlin’s reflection interface for a function declaration or callable function value. A function reference such as ::foo produces a KFunction value that can be invoked dynamically. section 12.2.1

Calling a function reference

fun foo(x: Int) = println(x) val kFunction = ::foo kFunction.call(42) // 42 call accepts arguments through a generic vararg interface. Passing the wrong number of arguments compiles but throws IllegalArgumentException at runtime. section 12.2.1

Prefer typed invocation when possible

fun sum(x: Int, y: Int) = x + y val kFunction: KFunction2<Int, Int, Int> = ::sum println(kFunction.invoke(1, 2)) println(kFunction(3, 4)) KFunction2 records two parameter types and the return type. invoke, or the equivalent direct call syntax, checks arity and types at compile time. section 12.2.1

The reflection hierarchy places KFunction alongside related callable interfaces:

  • KCallable supplies the generic call method for functions and property getters. section 12.2.1
  • KFunction0, KFunction1, and other KFunctionN interfaces specialize invocation by parameter count. section 12.3
  • KProperty and mutable-property interfaces represent reflected properties rather than functions. section 12.3

How Kotlin in Action, 2E covers it

How deep it goes
Explains generic call, typed invoke, direct calls, arity checking, and related interfaces without covering implementation internals.
Examples
Demonstrates ::foo with call and ::sum with KFunction2, invoke, direct calls, and invalid-arity diagnostics.
What it assumes
Assumes basic Kotlin functions and function-reference syntax, then develops callable interfaces and reflective invocation.
What you can do after
Apply it via Kotlin reflection to invoke referenced functions generically or with compile-time parameter checks.
How it connects
Connects KFunction with KCallable, KProperty, function references, and the Kotlin reflection API.

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.