liveBook · Manning

KCallable.callBy

As explained in Kotlin in Action, 2E

KCallable.callBy is a Kotlin reflection API operation that invokes a callable using a map from parameters to argument values and can apply default parameter values.

KCallable.callBy invokes a Kotlin function or constructor from a map of KParameter keys to argument values. Unlike call, it can use default parameter values when arguments are omitted, and map entries need not follow declaration order. section 12.2.5

Reflective construction from named data

A deserializer can read a constructor’s parameter names from JSON, resolve each name to a KParameter, convert the value to the parameter’s KType, and invoke the constructor with constructor.callBy(arguments). A missing parameter uses its default value when possible, so callers need not include defaulted properties in the JSON. section 12.2.5

Using callBy reliably requires three checks:

  • Use KParameter keys rather than positional argument indexes; callBy accepts a Map<KParameter, Any?>. section 12.2.5
  • Match every supplied value to the constructor parameter type. Incorrect values cause IllegalArgumentException at run time, especially when converting JSON numbers to Int, Long, or Double. section 12.2.5
  • Use KParameter.type to select or apply a suitable ValueSerializer, including custom serializers where configured. section 12.2.5
interface KCallable<out R> {
   fun callBy(args: Map<KParameter, Any?>): R
   // ...
}

The core signature makes the contract explicit: callBy receives a parameter-to-value map and returns the callable’s result. section 12.2.5

How Kotlin in Action, 2E covers it

How deep it goes
Explains mapped invocation, default arguments, type conversion, and runtime failures, but defers callBy’s internal implementation.
Examples
Uses JSON constructor arguments, numeric type conversion, ValueSerializer mappings, and BooleanSerializer as implementation examples.
What it assumes
Assumes familiarity with Kotlin reflection and parameter maps while teaching type lookup and default-argument handling through deserialization.
What you can do after
Apply it to invoke reflective constructors or functions with named arguments and supported default values.
How it connects
Connects KCallable with KFunction, KProperty, KParameter, KType, reflection, default parameter values, and deserialization.

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.