Kotlin tips #2: Infix functions

Today’s tips is about something I recently found and which blown my mind: Infix functions.

Julien Piatek
1 min readOct 7, 2018

What is an infix function ?

Let’s suppose you have a Food class, like this one :

And you also have a Human class, which possess a method which allow him to eat some food :

To make an Human object eats a Food object, you’ll have to write :

human.eats(food)

Now let’s turn it to an infix function:

By making the eat method infix, Now you can call it as below :

human eats food

Wow wait where are the parenthesis, and the dot man ?

They are gone, Kotlin allows you to achieve this level of readability. Still, keep in mind that infix functions can’t have more that one single parameter.

Infix function can also be written as extensions functions :

Keep in mind that using this feature too much can also make your code less readable. With great power comes great responsibility.

--

--

Julien Piatek

Passionated about tech and the future we can build with it.