You are currently viewing Infix Function

Infix Function

In Kotlin, infix functions allow you to call functions with a single argument without using the traditional dot and parentheses syntax. This can make your code more readable and expressive, especially when you’re working with DSLs (Domain Specific Languages) or building fluent APIs.

To define an infix function in Kotlin, you need to:

  • Mark the function with the infix keyword.
  • Define the function as an extension function or a member function of a class or a top-level function.

Here’s an example of an infix function:

infix fun Int.plusTwo(other: Int): Int {
    println(this) // 3
    return this + other + 2

fun main() {
    val result = 3 plusTwo 5 // Equivalent to 3.plusTwo(5)
    println(result) // Output: 10

In this example, we’ve defined an infix function plusTwo that takes an Int as an argument and adds it to the receiver (this) and another integer, plus 2. In the main function, you can see how the infix notation works.

Keep in mind that there are some limitations:

  • Infix functions must be members or extension functions.
  • They must have exactly one parameter.
  • The parameter cannot have a default value.