Idiomatic Kotlin: Infix functions

Tompee Balauag
Familiar Android
Published in
2 min readJul 6, 2018
Photo by Patrick Tomasso on Unsplash

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.

  1. Must be a member function or an extension function
  2. Must have a single parameter
  3. 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.

  1. Extension Functions
  2. Sealed Classes
  3. Infix Functions
  4. Class Delegation
  5. Local functions
  6. Object and Singleton
  7. Sequences
  8. Lambdas and SAM constructors
  9. Lambdas with Receiver and DSL
  10. Elvis operator
  11. Property Delegates and Lazy
  12. Higher-order functions and Function Types
  13. Inline functions
  14. Lambdas and Control Flows
  15. Reified Parameters
  16. Noinline and Crossinline
  17. Variance
  18. Annotations and Reflection
  19. Annotation Processor and Code Generation

--

--