liveBook · Manning

isOptional

As explained in Kotlin in Action, 2E

isOptional is a Kotlin reflection property that indicates whether a callable parameter has a default value and may be omitted.

isOptional is a Kotlin reflection property on KParameter. It is true when a callable parameter has a default value and may be omitted from a callBy argument map. section 12.2.5

Checking which constructor arguments may be omitted

private fun ensureAllParametersPresent(arguments: Map<KParameter, Any?>) { for (param in constructor.parameters) { if (arguments[param] == null && !param.isOptional && !param.type.isMarkedNullable) { throw JKidException("Missing value for parameter ${param.name}") } } } section 12.2.5

Use isOptional to distinguish constructor parameters during reflective deserialization:

  • Omit an argument when isOptional is true; the callable supplies its default value. section 12.2.5
  • Supply null for a parameter whose type is nullable when no value is present. section 12.2.5
interface KCallable<out R> {
   fun callBy(args: Map<KParameter, Any?>): R
   // ...
}

KCallable.callBy accepts a map keyed by KParameter, providing the reflective call mechanism where optional parameters can be omitted. section 12.2.5

How Kotlin in Action, 2E covers it

How deep it goes
Explains default-value detection and validation alongside nullable parameters, but does not descend into compiler implementation.
Examples
Uses constructor-argument validation during JSON deserialization as its concrete example.
What it assumes
Assumes Kotlin reflection and callable parameters while teaching optional, nullable, and required-argument distinctions.
What you can do after
Apply it via Kotlin reflection to validate and assemble arguments for reflective calls.
How it connects
Connects Kotlin reflection, KParameter, callBy, default parameter values, nullable types, and constructor parameters.

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.