Infix Functions
Discover what infix functions are and how you can implement your own to write more readable Kotlin code.
We'll cover the following
Infix functions are a great tool to improve readability of function calls in certain cases.
What are Infix Functions? #
In programming, function calls are typically written in prefix notation, meaning that the function name is in front, followed by its arguments in parentheses:
gcd(54, 24)
With infix functions, however, the function name stands between the arguments. You’ve already seen this with the predefined to
function, which creates Pair
s (to put into a map):
"Dwayne" to 3.14159
Here, the function name to
is surrounded by its two arguments, which brings us to the first limitation of infix functions: an infix function must have exactly two parameters. In the function call, the first argument is on the left of the function name, and the second is on the right. Infix function calls don’t need parentheses, which helps remove clutter from your code.
Other infix functions you have already seen include
downTo
andstep
.
You can still call an infix function like a regular function as well. The following is equivalent to the example above:
to("Dwayne", 3.14159)
However, you can see that this significantly weakens code readability. Infix functions can improve readability for functions where it leads to a natural way of reading the function call.
Implementing an Infix Function #
Kotlin has a function to repeat a string a given number of times:
Get hands-on with 1400+ tech skills courses.