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
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With