我在Kotlin中定义了一个枚举SupportUsLevel
。它的原始类型是字符串(出于其他原因),但是为了方便比较,我将numeric
值作为Int
包括在内。我想将此枚举与另一个枚举进行比较,但该枚举也可以为null。因此,我实现了一个compareTo运算符,该运算符采用可为空的other
:
enum class SupportUsLevel(val value: String) {
red("red"),
blue("blue"),
black("black");
val numeric: Int
get() {
when (this) {
red -> return 1
blue -> return 5
black -> return 7
}
}
//return 0 if equal, negative (-1) is smaller, positive(+1) is bigger
operator fun SupportUsLevel.compareTo(other: SupportUsLevel?) : Int {
//if other is null, since I cannot be null, I am always bigger
if (other == null) {
return 1
}
//return numeric comparison since we both now have a value (due to null-check before)
return numeric.compareTo(other.numeric)
}
}
但是,当我要使用它时,它表明编译器无法识别此自定义comparTo?我遇到类型不匹配的情况:
答案 0 :(得分:0)
实例方法总是优先于扩展方法(请参见org问题中的JB Nizet的注释),这意味着自定义定义的compareTo永远不会被编译器识别。
我能找到的最佳解决方案是使其成为标准成员函数
(请注意,它不再是一个比较,而是一个isHigherThen
(...),因为这是我需要的):
enum class SupportUsLevel(val value: String) {
//since we are using the standard enum compare operator the order must be low to high!
//refer to https://stackoverflow.com/questions/53456649/enum-compareto-operator-overloading-with-nullable-value
red("red"),
blue("blue"),
black("black");
val numeric: Int
get() {
when (this) {
red -> return 1
blue -> return 5
black -> return 7
}
}
fun isHigherThen(other: SupportUsLevel?) : Boolean {
//if other is null, since I cannot be null, I am always bigger
if (other == null) { return true }
//return numeric comparison since we both now have a value (due to null-check before)
return numeric > other.numeric
}
}