Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to implement Comparable interface on Kotlin Enum

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
like image 934
Arturs Vancans Avatar asked Sep 12 '25 14:09

Arturs Vancans


1 Answers

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

sealed class Fruit(val name: String) : Comparable<Fruit> {
    override fun compareTo(other: Fruit): Int = this.name.compareTo(other.name)
}

data object Apple    : Fruit("apple")
data object Orange   : Fruit("orange")
data object Zucchini : Fruit("zucchini")

fun main() {
    println(Apple < Orange)    // true
    println(Orange < Zucchini) // true
}
like image 156
David Soroko Avatar answered Sep 14 '25 05:09

David Soroko