— Kotlin, Functions — 1 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.
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.
To declare an infix function, we must follow these rules:
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 function11 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.
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.y4
5infix fun Point.isRightOf(other: Point) = x > other.x6
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 p22p2 is right of p1
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!