Idiomatic Kotlin: Infix functions
This article is a part of the Idiomatic Kotlin series. The complete list is at the bottom of the article.
In this article we will be talking about infix functions and what makes them cool.
What is an Infix function?
An infix function is a function that can be invoked via infix notation. It is a special type of function and has specific rules to satisfy. One of the most common infix function is the to
function to create a Pair
object. It can be invoked in this way
1 to "apple"
instead of
1.to("apple")
and still produce the same Pair<Int, String>
object.
Motivation
Infix notation is more like a syntactic sugar. It makes our code closer to our natural language and makes it easier to read.
How to create an Infix function
To create an infix function, the following rules must be satisfied.
- Must be a member function or an extension function
- Must have a single parameter
- Parameter is not
vararg
and has no default value.
As soon as your function satisfies the above condition, converting it to an infix function is as easy as adding the modifier infix
to your function definition.
Infix function under the hood
As an example, let us define a warrior class with a hp(hit points) and ap(attack points) properties. We also add an attack method as an infix function.
Running this will output
Warrior 2 HP : 80
Now let us look at the decompiled code
Notice that the attack was converted into a normal function call. Nothing special. No conversion or any overhead.
Some considerations
Infix functions have their own position in operator precedence. For more information, check this table.
When calling infix function inside the class that it is defined, it is important to explicitly use this
.
That’s it for the infix function. Check out the other articles in the idiomatic kotlin series. The sample source code for each article can be found here in Github.
- Extension Functions
- Sealed Classes
- Infix Functions
- Class Delegation
- Local functions
- Object and Singleton
- Sequences
- Lambdas and SAM constructors
- Lambdas with Receiver and DSL
- Elvis operator
- Property Delegates and Lazy
- Higher-order functions and Function Types
- Inline functions
- Lambdas and Control Flows
- Reified Parameters
- Noinline and Crossinline
- Variance
- Annotations and Reflection
- Annotation Processor and Code Generation