Jagdeep SinghJagdeep Singh
Navigate back to the homepage

The fun of Kotlin — Infix Functions

Jagdeep Singh
April 4th, 2021 · 1 min read

The fun of Kotlin — Infix Functions

In the previous part of this series, we learned about Local functions in Kotlin. I this part, I’d like to talk about Infix functions. Infix notation makes function calls look super awesome.

Pit stops

  1. Local functions.
  2. Infix functions. (you’re here)
  3. Anonymous functions.
  4. Inline functions.
  5. Returns and local returns.

Who should read?

This post is for all the Kotlin lovers and those people who are learning or want to learn Kotlin.

Prerequisite

I’d recommend that, before moving forward, you have basic knowledge of Kotlin language syntax such as how to define variables, classes and functions. Official website of Kotlin is the best place to learn the basic syntax of the language.

Infix functions

Functions marked with the infix keyword can also be called using the infix notation (omitting the dot and the parentheses for the call). Infix functions must satisfy the following requirements:

Example of infix notation in Kotlin

1infix fun String.shouldBeSame(other: String) = this == other
2
3// calling the function using the infix notation
4"bello" shouldBeSame "bello"
5
6// is the same as
7"hello".shouldBeSame("hello")

On the left side, is the receiver instance on which you’ll define infix function. On the right side, is a parameter that will be passed to the infix function.

I think the best use case for infix notation is to make argument matchers in testing frameworks more readable and create nice looking APIs.

Example — Kotlin test framework

kotlintest/kotlintest

Kotlintest is a testing framework for Kotlin. It uses infix notation extensively to make really nice looking APIs. Here is a snippet of their API.

Clean API of kotlintest using infix notation

1"substring" should include("str")
2
3user.email should beLowerCase()
4
5a + b shouldBe result

Official documentation of Infix notation

Checkout more examples of Kotlin function in my sample GitHub project.

jdsingh/kotlin-functions-examples


Thank you for taking your time to read this article. If you have any questions, suggestions on how to improve this articles, please feel free to contact me on twitter :)

Jagdeep Singh (@jsmundi)

More articles from Jagdeep Singh

Realtime access to production logs — Android

Papertrail-timber gives you an already configured Timber Tree that you can just plant in Timber and ready to go.

March 7th, 2018 · 2 min read

The fun of Kotlin - Local Functions

In Kotlin, functions are the first class citizens. In this series I'll be talking about some super cool features of Kotlin functions.

April 4th, 2021 · 1 min read
© 2018–2021 Jagdeep Singh
Link to $https://twitter.com/jsmundi/Link to $https://github.com/jdsingh/Link to $https://www.linkedin.com/in/jagdeepsinghmundi/