Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

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?

like image 932
Elye Avatar asked Feb 02 '26 22:02

Elye


1 Answers

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.

like image 88
s1m0nw1 Avatar answered Feb 05 '26 12:02

s1m0nw1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!