liveBook · Manning

Infix function

As explained in Kotlin in Action, 2E

An infix call is Kotlin call syntax that places a one-parameter function name between its receiver and argument without parentheses or other separators.

An infix call places a one-parameter function between its receiver and argument, removing parentheses and other separators. The syntax makes operator-like calls concise while remaining an ordinary function invocation. section 3.4.3 section 3.7

1.to("one")    #1
1 to "one"     #2

These two calls are equivalent; the second uses infix notation. section 3.4.3

Use infix notation only when the function satisfies these requirements:

Building pairs and maps

The standard-library extension function to creates a Pair, so `1 to "one"` reads more naturally than `1.to("one")`. Pair values can feed mapOf and can later be unpacked with a destructuring declaration. section 3.4.3

Readable test DSLs

In Kotest, `s should startWith("K")` chains an infix should function with a matcher, producing assertion code that reads almost like English while remaining statically typed. section 13.4.1

How Kotlin in Action, 2E covers it

How deep it goes
Defines the syntax rules and demonstrates pairs and DSLs, but does not descend into compiler implementation.
Examples
Uses to for Pair creation, mapOf for maps, and should with startWith for Kotest assertions.
What it assumes
Assumes basic Kotlin function usage and introduces the relevant Pair and destructuring patterns through examples.
What you can do after
Apply infix syntax to one-parameter functions and construct readable Kotest-style DSL expressions.
How it connects
Connects infix functions with extension functions, Pair, destructuring declarations, collections, operator overloading, and internal DSLs.

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.