Kotlin Infix Notation is Confusing

If you see a method call that have space between, it is likely a Kotlin infix notation.

ยท

1 min read

Kotlin Infix Notation is Confusing

Whenever I read Kotlin code that has infix notation, it always confuses me. Maybe I should say I still haven't gotten used to it? Honestly, it is just sugar syntax in my opinion.

For example:

val result = 2 plus 3

is the same as

val result = 2.plus(3)

2 is the Int object. plus() is the method of Int. 3 is Int parameter for Int.plus()

The plus() method definition looks like this. It is an extension method of Int.

infix fun Int.plus(other: Int): Int {
    return this + other
}

Another good example is plugins in the build.gradle.kts file.

plugins {
    id("com.android.application") version "7.4.2" apply false
}

Can you see the spaces between the version and apply? Yupe, these are the infix functions.

You can rewrite it to

plugins {
    id("com.android.application").version("7.4.2").apply(false)
}

These are the function signatures. As you can see, infix notation is used.

infix fun PluginDependencySpec.version(version: String?): PluginDependencySpec = version(version)

infix fun PluginDependencySpec.apply(apply: Boolean): PluginDependencySpec = apply(apply)

There are some specific requirements that you must follow to define an infix function:

  • Must be methods/member functions (functions in a class)

  • Must have a single parameter with no default value

For details, you can refer to the official doc here.

ย