0

由于某些原因。我无法为运算符定义扩展运算符函数,++同时--能够为相同的运算符定义成员运算符函数。

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
object _12_IncrementAndDecrementOperatorsCantBeExtensionFunctions_Test {
    private class X {
        operator fun inc(): X = X()
        operator fun dec(): X = X()
    }

    private class Y

    /*Compile-time | 'operator' modifier is inapplicable on this function: receiver must be a supertype of the return type*/
    private operator fun Y.inc(): Y = Y()

    /*Compile-time | 'operator' modifier is inapplicable on this function: receiver must be a supertype of the return type*/
    private operator fun Y.dec(): Y = Y()
}

我错过了什么吗?有这种限制的原因吗?

4

1 回答 1

2

如果您在对象之外定义运算符,它将起作用_12_IncrementAndDecrementOperatorsCantBeExtensionFunctions_Test

class Y

operator fun Y.inc(): Y = Y()

operator fun Y.dec(): Y = Y()

这实际上是 Kotlin 中的一个错误:https ://youtrack.jetbrains.com/issue/KT-24800

于 2020-08-13T07:58:04.113 回答