Skip to content
DeveloperMemos

Infix Functions in Kotlin

Kotlin, Functions1 min read

Kotlin is a modern programming language that allows developers to write concise and expressive code. One of the features that contribute to this expressiveness is infix functions.

What are Infix Functions?

Infix functions are a type of function in Kotlin that allow us to call a method or function using an infix notation instead of the regular dot notation. This means that instead of calling a function like this:

1val result = myObject.myFunction(argument)

We can call it like this:

1val result = myObject myFunction argument

This is possible because we declare our function with the infix keyword.

Syntax

To declare an infix function, we must follow these rules:

  1. The function must be a member function or an extension function.
  2. The function must have a single parameter.
  3. The parameter must not accept variable arguments or be nullable.
  4. The function must be marked with the infix keyword.

Here's an example of an infix function:

1class Person(val name: String) {
2 infix fun says(message: String) {
3 println("$name says: $message")
4 }
5}
6
7fun main() {
8 val person = Person("John")
9
10 // Call the infix function
11 person says "Hello, World!"
12}

The output of this program will be:

1John says: Hello, World!

As you can see, the says function is declared as an infix function by using the infix keyword. We can call the function using the infix notation, which makes the code more readable.

Using Infix Functions

Infix functions are useful when we want to create domain-specific languages or DSLs. They allow us to create code that reads like natural language. Here's an example:

1data class Point(val x: Int, val y: Int)
2
3infix fun Point.isAbove(other: Point) = y < other.y
4
5infix fun Point.isRightOf(other: Point) = x > other.x
6
7fun main() {
8 val p1 = Point(1, 4)
9 val p2 = Point(2, 2)
10
11 if (p1 isAbove p2) {
12 println("p1 is above p2")
13 }
14
15 if (p2 isRightOf p1) {
16 println("p2 is right of p1")
17 }
18}

In this code, we define two infix functions that compare two points. We can then use these functions to create natural language expressions that read like English. The output of this program will be:

1p1 is above p2
2p2 is right of p1

Conclusion

Infix functions are a powerful feature of Kotlin that allow us to write more expressive code. They are easy to use and can help us create domain-specific languages that read like natural language. Knowing how to use them can make your code more readable and understandable, so give them a try!