liveBook · Manning

Named argument

As explained in Kotlin in Action, 2E

Named-argument syntax specifies function or constructor arguments by writing each argument's parameter name explicitly.

Named-argument syntax makes Kotlin calls clearer by writing parameter names beside their values. It is especially useful when several arguments share a type or represent Boolean choices. section 3.2.1

Making a collection call readable

A positional call can hide which value means what: joinToString(collection, " ", " ", ".") Kotlin makes the parameters explicit: joinToString(collection, separator = " ", prefix = " ", postfix = ".") You may name only selected arguments. When every argument is named, you may also reorder them: joinToString( postfix = ".", separator = " ", collection = collection, prefix = " " ) section 3.2.1

Use named arguments to:

  • Expose the meaning of arguments in calls with many parameters. section 3.2.1
  • Combine explicit names with default parameter values, omitting values that do not need customization. section 3.2.1
  • Construct objects clearly, as in Person("Alice", age = 29), while leaving omitted parameters at their defaults. section 1.1
  • Apply Kotlin annotations with explicit constructor parameter names; Java annotations require names for specified attributes except value. section 12.1.4
  • Keep argument names synchronized after parameter renaming through IDE refactoring actions. section 3.2.1
joinToString(collection, separator = " ", prefix = " ", postfix = ".")

Compare a positional joinToString call with its named-argument form. section 3.2.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains partial naming, complete-call reordering, default-value combinations, IDE refactoring, and Java annotation restrictions.
Examples
Uses joinToString calls, Person construction, and Kotlin-versus-Java annotation applications.
What it assumes
Assumes basic Kotlin familiarity and compares behavior with familiar Java function-call and annotation conventions.
What you can do after
Apply named arguments to make Kotlin function, constructor, and annotation calls more readable and maintainable.
How it connects
Connects named arguments with default parameter values, function calls, constructors, annotations, and Java interoperability.

Also explained in

Compare how 3 books explain named argument →

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.