ProgrammingBackend Developer

What are infix functions in Kotlin, how to declare and properly use them, and what limitations exist? Provide an example of creating your own infix function and discuss the pitfalls.

Pass interviews with Hintsage AI assistant

Answer.

Infix function is a function that can be called in infix form (without a dot and parentheses), which enhances code readability. Such functions are convenient, for instance, for creating DSLs (domain-specific languages).

How to declare an infix function:

  • The function must be a method of a class/extension function.
  • It must have exactly one parameter.
  • It is declared with the infix modifier.
  • It does not allow the use of vararg and default value for the parameter.

Example:

infix fun Int.add(x: Int): Int = this + x val result = 5 add 10 // 15

Advantages:

  • Increased readability, especially for calculations or chains of calls.
  • Applicable for building collections, condition checks (for example, x to y).

Limitations and pitfalls:

  • Infix is only available for methods with ONE mandatory parameter.
  • The execution priority of infix is lower than that of comparison and arithmetic operators (which sometimes leads to surprises with operation priorities).
  • Infix function does not work with default parameters and vararg.

Trick question.

Can an infix function be used with multiple parameters or with default parameters?

Answer: No, it can't. An infix function can have exactly one mandatory parameter without a default value and without vararg.

Example of an invalid declaration:

// Error! infix fun foo(a: Int, b: Int) { }

Examples of real mistakes due to ignorance of the nuances of the topic:


Story

In the project, there was an attempt to implement an infix function to replace builder function calls with more readable infix expressions. Due to ignorance of the limitation on the number of parameters, the function was declared with two parameters — students struggled to understand why the compilation was failing.


Story

A developer used infix expressions in a large arithmetic expression without parentheses, believing that the operation priority was the same as that of traditional mathematical operators. As a result, the expressions were computed differently than expected — had to rewrite with explicit parentheses.


Story

Inside a collection, pairing was implemented through infix ("item to value") and applied within nesting, however, due to misunderstanding of the syntax, two nested infix calls did not work — only a pair assignment at the top level worked, nested pairs were ignored, leading to losses of significant data.