我可以在自己的类中应用中缀函数而不使用“this”吗?

Ely*_*lye 3 kotlin

在 Kotlin 中,我们有中缀

例如当我们有

fun Int.test(value: Int) {}
Run Code Online (Sandbox Code Playgroud)

我们可以用

1.test(2)
Run Code Online (Sandbox Code Playgroud)

当我们添加中缀时

infix fun Int.test(value: Int) {}
Run Code Online (Sandbox Code Playgroud)

我们可以用作

1 test 2
Run Code Online (Sandbox Code Playgroud)

对于一个班级来说,以下是可以的

class myclass {
    fun main() {
        test(1)
    }
    fun test(value: Int) {}
}
Run Code Online (Sandbox Code Playgroud)

但是使用中缀以下是不行的

class myclass {
    fun main() {
        test 1
    }
    infix fun test(value: Int) {}
}
Run Code Online (Sandbox Code Playgroud)

显然,它必须有

class myclass {
    fun main() {
        this test 1
    }
    infix fun test(value: Int) {}
}
Run Code Online (Sandbox Code Playgroud)

我可以省略this, 因为testis call 在类本身内吗?

s1m*_*nw1 5

它不能省略,使用infix函数时总是需要一个左操作数,这就是this您的情况:

receiver functionName parameter

没有办法解决这个问题。