0

For some reason. I am unable to define an extension operator function for the operators ++ and -- while being able to define member operator functions for the same operators.

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

Am i missing something? Is there a reason for that limitation?

1 Answers1

2

It will work if you define the operators outside of the _12_IncrementAndDecrementOperatorsCantBeExtensionFunctions_Test object:

class Y

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

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

It's actually a bug in Kotlin: https://youtrack.jetbrains.com/issue/KT-24800

Mafor
  • 9,668
  • 2
  • 21
  • 36