The fun of Kotlin — Infix Functions
In the previous part of this series, we learned about Local functions in Kotlin. I this part, I’d like to talk about Infix functions. Infix notation makes function calls look super awesome.
- Local functions.
- Infix functions. (you’re here)
- Anonymous functions.
- Inline functions.
- Returns and local returns.
Who should read?
This post is for all the Kotlin lovers and those people who are learning or want to learn Kotlin.
I’d recommend that, before moving forward, you have basic knowledge of Kotlin language syntax such as how to define variables, classes and functions. Official website of Kotlin is the best place to learn the basic syntax of the language.
Functions marked with the infix keyword can also be called using the infix notation (omitting the dot and the parentheses for the call). Infix functions must satisfy the following requirements:
- They must be member functions or extension functions.
- They must have a single parameter.
- The parameter must not accept variable number of arguments and must have no default value.
Example of infix notation in Kotlin
1infix fun String.shouldBeSame(other: String) = this == other23// calling the function using the infix notation4"bello" shouldBeSame "bello"56// is the same as7"hello".shouldBeSame("hello")
On the left side, is the receiver instance on which you’ll define infix function. On the right side, is a parameter that will be passed to the infix function.
I think the best use case for infix notation is to make argument matchers in testing frameworks more readable and create nice looking APIs.
Example — Kotlin test framework
Kotlintest is a testing framework for Kotlin. It uses infix notation extensively to make really nice looking APIs. Here is a snippet of their API.
Clean API of kotlintest using infix notation
1"substring" should include("str")23user.email should beLowerCase()45a + b shouldBe result
Checkout more examples of Kotlin function in my sample GitHub project.
Thank you for taking your time to read this article. If you have any questions, suggestions on how to improve this articles, please feel free to contact me on twitter :)