【问题标题】:Unable To Define An Operator Extension Function For The Increment and Decrement Operators无法为递增和递减运算符定义运算符扩展函数
【发布时间】:2020-08-13 06:58:45
【问题描述】:

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

@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()
}

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

【问题讨论】:

    标签: kotlin operator-overloading increment decrement extension-function


    【解决方案1】:

    如果您在 _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

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 2015-02-16
      • 1970-01-01
      • 2015-10-03
      • 2014-03-21
      • 2010-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多