The difference between infix function and operator in Kotlin
Hello everyone. Many of us use infix functions that come with Kotlin standard library as a replacement for operators. Since they have inline keyword and give us the same runtime performance as operators, you may think of them as just a named version of operators. But they are not totally the same as operators and today we will know why!
To help us understand the difference, let’s first talk about how an expression is evaluated in programming languages in general.
Expressions Evaluation
In a programming language, each expression has precedence in parsing, for example *
and /
has higher precedence than *
and —
that is what makes expressions like 2 * 2 + 2
evaluated to 6
not 8
because 2 * 2
will be evaluated first.
But what if two expressions have the same precedence? Which one will be evaluated first?
In this case, they will be evaluated from left to right; for example 1 + 2 + 3
will evaluate 1 + 2
first then 3 + 3
.
Now let's back to our main question about infix functions vs operators.
Infix functions vs operators
Infix function is just a syntax sugar that represents a function that takes two parameters but can call like an operator between two expressions. For example a function b
is actually function(a, b)
and from the compiler perspective, the infix function name is just a name like any other function. So if you named it and
or plus
that doesn’t mean compiler will trait it like &&
or +
operator and this is the main difference and that can cause big problems if you forget this simple difference, take this example.
true || false && false
true or false and false
They look almost the same, but once you evaluate them you will find that they have a different result. Let’s see how they are evaluated.
The first expression
true || false && false
In this expression, the and ( &&
) operator has higher precedence than the or ( ||
) operator so it will evaluate first false && false
will be evaluated to false
and now our expression looks like true || false
and finally evaluated to true
.
The second expression
true or false and false
This expression has no operators. They are two infix functions, and from the compiler prescriptive, they have the same precedence. So they will be evaluated from left to right, first true or false
will be evaluated to true
so our expression will be true and false
and this will be evaluated to false
.
Conclusion
When you want to use infix functions, make sure you explicitly know which part will be evaluated first and you can control that using Group expression (..)
because expression inside Group always has the highest precedence and will be evaluate first.
I hope you enjoyed my article and you can find me on
You can find me on: GitHub, LinkedIn, Twitter.
Enjoy Programming 😋.