kotlin - 如何制作 Kotlin 可比类型?

标签 kotlin

刚刚学习定义一个 DateRange 类型

val wholeYear2017 = Date(2017,1,1)..Date(2017,12,31)

所以我创建了如下类型

class DateRange<Date: Comparable<Date>>(override val start: Date, override val endInclusive: Date)
    : ClosedRange<Date>

class Date (val year: Int, val month: Int, val day: Int) {

    operator fun compareTo(other: Date): Int {
        if (this.year > other.year) return 1
        if (this.year < other.year) return -1
        if (this.month > other.month) return 1
        if (this.month < other.month) return -1
        if (this.day > other.day) return 1
        if (this.day < other.day) return -1
        return 0
    }

    operator fun rangeTo(that: Date): DateRange = DateRange(this, that)
}

但是我得到一个编译错误

One type of argument expected for class DateRange<Date: Comparable<Date>> : ClosedRange<Date>

我错过了什么?我做对了吗?

最佳答案

你需要实现Comparable接口(interface)。您可以使用 compareValuesBy 辅助函数:

data class Data(
        val a: Int,
        val b: Int
) : Comparable<Data> {
    override fun compareTo(other: Data) = compareValuesBy(this, other,
            { it.a },
            { it.b }
    )
}

关于kotlin - 如何制作 Kotlin 可比类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46484879/

相关文章:

java - 扫描我的二维码后即可进行下一个 Activity

android - 如何重新启动已取消的作业?

java - Spring 启动 : Change property placeholder signifier

kotlin - Kotlin 中的 tailrec 函数无法返回阶乘结果

gradle - Unresolved reference :sourceSets-Gradle Kotlin DSL在另一个文件中

android - 在 safeArgs 中将 ArrayList 作为参数传递

android - "onCreateView overrides nothing"

java - 在 Java 类中调用 Kotlin 挂起函数

android - AppModule.provideViewModelFactories(AppModule.kt) 处的 NoClassDefFoundError

android - 在 Android 10 上从 contentProvider 加载所有图像