Elye
Elye

Reputation: 60131

Can I apply infix function within the own class without `this`?

In Kotlin, we have infix

e.g. when we have

fun Int.test(value: Int) {}

We can use

1.test(2)

And when we put infix

infix fun Int.test(value: Int) {}

We can use as

1 test 2

For a class, the below is okay

class myclass {
    fun main() {
        test(1)
    }
    fun test(value: Int) {}
}

But with infix the below is not okay

class myclass {
    fun main() {
        test 1
    }
    infix fun test(value: Int) {}
}

Apparently, it has to have

class myclass {
    fun main() {
        this test 1
    }
    infix fun test(value: Int) {}
}

Can I omit this, since test is call within the class itself?

Upvotes: 3

Views: 786

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 81939

It can't be omitted, you always need a left operand when using infix functions, which is this in your case:

"receiver functionName parameter"

There's no way around it.

Upvotes: 5

Related Questions