Kotlin Infix Notation is Confusing

vtsen

Vincent Tsen

Posted on April 8, 2023

Kotlin Infix Notation is Confusing

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

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
Enter fullscreen mode Exit fullscreen mode

is the same as

val result = 2.plus(3)
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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

plugins {
    id("com.android.application") version "7.4.2" apply false
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.


Originally published at https://vtsen.hashnode.dev.

💖 💪 🙅 🚩
vtsen
Vincent Tsen

Posted on April 8, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related