HomeAndroidKotlin Infix Notation is Complicated

Kotlin Infix Notation is Complicated


At any time when I learn Kotlin code that has infix notation, it all the time confuses me. Perhaps I ought to say I nonetheless have not gotten used to it? Truthfully, it’s simply sugar syntax in my view.

For instance:

val end result = 2 plus 3

is similar as

val end result = 2.plus(3)

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

The plus() technique definition seems like this. It’s an extension technique of Int.

infix enjoyable Int.plus(different: Int): Int {
    return this + different
}

One other good instance is plugins within the construct.gradle.kts file.

plugins {
    id("com.android.software") model "7.4.2" apply false
}

Are you able to see the areas between the model and apply? Yupe, these are the infix features.

You’ll be able to rewrite it to

plugins {
    id("com.android.software").model("7.4.2").apply(false)
}

These are the perform signatures. As you may see, infix notation is used.

infix enjoyable PluginDependencySpec.model(model: String?): PluginDependencySpec = model(model)

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

There are some particular necessities that you should comply with to outline an infix perform:

For particulars, you may discuss with the official doc right here.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments