← Back to Kotlin Course | Chapter 4: Functions | Lesson 6 of 7

Infix Functions

An infix function lets you call a function by writing it between two values, like 3 to 4, instead of using dots and parentheses.

What Makes a Function Infix

Adding the infix keyword before fun allows the function to be called by placing its name between the receiver and the single argument, without a dot or parentheses.

Note: Infix functions must take exactly one parameter.

Example: What Makes a Function Infix

markup
infix fun Int.timesRepeated(action: () -> Unit) {
    repeat(this) { action() }
}

fun main() {
    3 timesRepeated { println("Hi!") }
}

The Built-in to Infix Function

The standard library's to function is infix, creating a Pair from two values with clean, readable syntax: "key" to "value".

Example: The Built-in to Infix Function

markup
fun main() {
    val entry = "name" to "Kotlin"
    println("${entry.first} = ${entry.second}")
}

Boolean Infix Functions

and, or, and xor are infix functions on Boolean (and on Int for bitwise operations), letting logical combinations read naturally.

Example: Boolean Infix Functions

markup
fun main() {
    val a = true
    val b = false
    println("a and b = ${a and b}")
    println("a or b = ${a or b}")
    println("a xor b = ${a xor b}")
}

Writing Your Own Infix Function

Custom infix functions are useful for small domain-specific operations that read naturally as a relationship between two values, such as combining two ranges.

Note: Reserve infix notation for operations that genuinely read like a natural verb or relation -- overusing it can obscure a normal function call.

Example: Writing Your Own Infix Function

markup
infix fun Int.upTo(end: Int): List<Int> = (this..end).toList()

fun main() {
    val range = 1 upTo 5
    println(range)
}
Common Mistakes
  1. Trying to mark a function infix with more than one required parameter; infix functions must take exactly one parameter.
  2. Forgetting infix functions must be member or extension functions, not top-level standalone functions in every case (they can be, but need a receiver).
  3. Overusing custom infix functions for things that are not naturally read as an operator-like relationship, hurting clarity.
Chapter Summary
  • Marking a function with the infix keyword lets it be called without a dot or parentheses, e.g. a to b.
  • An infix function must have exactly one parameter and be a member or extension function.
  • to (creating a Pair), and, or, and xor on Boolean/Int are common standard library infix functions.
  • Infix notation should be reserved for operations that read naturally like a verb or relation between two things.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.