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
