Infix Functions
3 to 4, instead of using dots and parentheses.In this page:
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
infix fun Int.timesRepeated(action: () -> Unit) {
repeat(this) { action() }
}
fun main() {
3 timesRepeated { println("Hi!") }
}
Login to try C/C++/Java/PHP code in the editor
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
fun main() {
val entry = "name" to "Kotlin"
println("${entry.first} = ${entry.second}")
}
Login to try C/C++/Java/PHP code in the editor
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
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}")
}
Login to try C/C++/Java/PHP code in the editor
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
infix fun Int.upTo(end: Int): List<Int> = (this..end).toList()
fun main() {
val range = 1 upTo 5
println(range)
}
Login to try C/C++/Java/PHP code in the editor
- Trying to mark a function
infixwith more than one required parameter; infix functions must take exactly one parameter. - Forgetting infix functions must be member or extension functions, not top-level standalone functions in every case (they can be, but need a receiver).
- Overusing custom infix functions for things that are not naturally read as an operator-like relationship, hurting clarity.
- Marking a function with the
infixkeyword 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 aPair),and,or, andxoronBoolean/Intare 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: