Kotlin 边界限制

文章目录

Kotlin 边界限制

传统方式

kotlin 复制代码
fun processScore(score: Int): Int {
    if (score < 0) {
        return 0
    } else if (score > 100) {
        return 100
    }
    return score
}

println(processScore(-10)) // 0
println(processScore(80)) // 80
println(processScore(120)) // 100

coerceIn

coerceIn():限制值的范围,超出范围则返回边界值。

kotlin 复制代码
fun processScore2(score: Int): Int {
    return score.coerceIn(0, 100)
}

println(processScore2(-10)) // 0
println(processScore2(80)) // 80
println(processScore2(120)) // 100

coerceAtLeast

coerceAtLeast():限制下限,低于下限值则返回下限值。

kotlin 复制代码
fun processScore3(score: Int): Int {
    return score.coerceAtLeast(0)
}

println(processScore3(-10)) // 0
println(processScore3(80)) // 80
println(processScore3(120)) // 120

coerceAtMost

coerceAtMost():限制上限,高于上限值则返回上限值。

kotlin 复制代码
fun processScore4(score: Int): Int {
    return score.coerceAtMost(100)
}

println(processScore4(-10)) // -10
println(processScore4(80)) // 80
println(processScore4(120)) // 100

自定义类型

kotlin 复制代码
// 自定义Comparable类
data class MyDate(val year: Int, val month: Int, val day: Int) : Comparable<MyDate> {
    override fun compareTo(other: MyDate): Int {
        return compareValuesBy(this, other,
                               { it.year }, { it.month }, { it.day })
    }
}

// 定义扩展函数
fun <T : Comparable<T>> T.coerceIn(min: T, max: T): T {
    if (this < min) {
        return min
    } else if (this > max) {
        return max
    }
    return this
}

fun processDate(date: MyDate): MyDate {
    val minDate = MyDate(2024, 1, 1)
    val maxDate = MyDate(2024, 12, 31)
    return date.coerceIn(minDate, maxDate)
}

val date = MyDate(2023, 2, 30)
println(processDate(date)) // MyDate(year=2024, month=1, day=1)
val date2 = MyDate(2024, 1, 1)
println(processDate(date2)) // MyDate(year=2024, month=1, day=1)
val date3 = MyDate(2025, 1, 1)
println(processDate(date3)) // MyDate(year=2024, month=12, day=31)
相关推荐
sang_xb1 小时前
Android 如何开启 16KB 模式
android·kotlin
马尚道1 天前
掌握Kotlin编程,从入门到精通:视频教程
kotlin·ai编程
Kapaseker1 天前
Compose 中实现凸角、凹角、切角、尖角
android·kotlin
yueqc12 天前
Kotlin 协程 Flow 操作符总结
kotlin·协程·flow
molong9312 天前
Kotlin 内联函数、高阶函数、扩展函数
android·开发语言·kotlin
低调小一2 天前
Kuikly 小白拆解系列 · 第1篇|两棵树直调(Kotlin 构建与原生承载)
android·开发语言·kotlin
Android-Flutter2 天前
kotlin - 正则表达式,识别年月日
java·kotlin
ROO_KIE3 天前
[Java、C语言、Python、PHP、C#、C++]——深度剖析主流编程语言的核心特性与应用场景
kotlin
alexhilton3 天前
Kotlin互斥锁(Mutex):协程的线程安全守护神
android·kotlin·android jetpack
太过平凡的小蚂蚁3 天前
Kotlin 异步数据流三剑客:Flow、Channel、StateFlow 深度解析
android·kotlin