Unable to implement Comparable interface on Kotlin Enum

Viewed 28

I would like my Enum values to be comparable with other types, for instance, String. I am not entirely sure why it complains and what the error means.

enum class Fruits(val value: String): Comparable<String>{
    Apple("apple"),
    Orange("orange");

    override fun compareTo(other: String): Int {
        return compareValuesBy(this.value, other)
    }
}

val test: Boolean = Fruits.Apple == "apple"

Error says:

Type parameter T of 'Comparable' has inconsistent values: Fruits, String
1 Answers

Perhaps sealed classes are better suited to implement comparable enum, something like:

sealed class Fruit : Comparable<Fruit> {
    open abstract val name: String
    override fun compareTo(other: Fruit): Int =
        this.name.compareTo(other.name)
}
object Apple  : Fruit() { override val name = "apple" }
object Orange : Fruit() { override val name = "orange" }


fun main() {
    println(Apple < Orange) // true
}
Related