Allow override enum operator compareTo

When defining custom enums, it’d be cool to allow overriding the compareTo operator…

enum class Swizzle {

    SWIZZLE_RED, SWIZZLE_FIRST(SWIZZLE_RED), SWIZZLE_CHANNEL_FIRST(SWIZZLE_RED),
    SWIZZLE_GREEN,
    SWIZZLE_BLUE,
    SWIZZLE_ALPHA, SWIZZLE_CHANNEL_LAST(SWIZZLE_ALPHA),
    SWIZZLE_ZERO,
    SWIZZLE_ONE, SWIZZLE_LAST(SWIZZLE_ONE),

    SWIZZLE_COUNT(SWIZZLE_LAST - SWIZZLE_FIRST + 1);

    constructor() {
        i = counterSwizzle++
    }

    constructor(swizzle: Swizzle) {
        i = swizzle.i
    }

    constructor(i: Int) {
        this.i = i
    }

    val i: Int

    operator fun plus(other: Swizzle) = i + other.i
    operator fun plus(other: Int) = i + other
    operator fun minus(other: Swizzle) = i - other.i
    operator fun minus(other: Int) = i - other
    operator fun times(other: Swizzle) = i * other.i
    operator fun times(other: Int) = i * other
    operator fun div(other: Swizzle) = i / other.i
    operator fun div(other: Int) = i / other
    operator fun mod(other: Swizzle) = i % other.i
    operator fun mod(other: Int) = i % other
    override operator fun compareTo(other: Swizzle) = i.compareTo(other.i)
}

 fun Swizzle.isChannel()= this >= SWIZZLE_CHANNEL_FIRST && this <= SWIZZLE_CHANNEL_LAST

https://youtrack.jetbrains.com/issue/KT-14277

1 Like

I would agree, it can be useful and shouldn’t be declared final in Enum