无法为递增和递减运算符定义运算符扩展功能

问题描述

由于某些原因。我无法为运算符++--定义扩展运算符功能,而能够为同一运算符定义成员运算符功能

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

我想念什么吗?有这种限制的原因吗?

解决方法

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...