Infix notations for functions
To bring our code closer to the natural language, Kotlin provides infix notations for the functions containing a single parameter. This way, we can invoke the function without using brackets. In this recipe, we are going to learn how to design an infix extension function for the String type, named concat(), which is responsible for the concatenation of two string values.
Getting ready
In order to enable an infix notation for the function, we simply need to add the infix keyword before the function header.
How to do it...
Declare the concat() extension function and implement its body:
infix fun String.concat(next: String): String = this + next
How it works...
Let's test the concat() function by running the following code:
print("This" concat "is" concat "weird")Great! We have just printed out the following text to the console:
ThisisweirdThere's more...
The Kotlin standard library uses the infix notation extensively. You can benefit from infix functions to shape your...