Kotlin - 边界控制 coerceIn、coerceAtLeast、coerceAtMost

一、概念

当需要对数值进行范围限制时,通常会用 if() else if() else,这样会写很多判断,使用 coerceXXX() 函数来简化,适用于实现了 Comparable 接口的对象。

|-----------------|------------------------------------------------------------------------------------------------------------|
| coerceIn() | public fun <T : Comparable<T>> T.coerceIn(minimumValue: T?, maximumValue: T?): T 限制数值在给定范围之内,超出则返回边界值。 |
| coerceAtLeast() | public fun <T : Comparable<T>> T.coerceAtLeast(minimumValue: T): T 确保值不小于指定最小值,小于则返回最小值。 |
| coerceAtMost() | public fun <T : Comparable<T>> T.coerceAtMost(maximumValue: T): T 确保值不大于指定最大值,大于则返回最大值。 |

Kotlin 复制代码
fun demo(age: Int) {
    val safeAge = age.corceIn(0, 130)
}
Kotlin 复制代码
data class Person(val age: Int) : Comparable<Person> {
    override fun compareTo(other: Person): Int {
        return this.age - other.age
    }
}

fun main() {
    val a = Person(1)
    val b = Person(3)
    val c = Person(5)
    val result = c.coerceIn(a, b)
    print(result)   //打印:Person(age=3)
}
相关推荐
mmsx1 天前
Android 防二次打包第一道锁:签名校验与完整性校验
android·kotlin
mmsx1 天前
Android 混淆不等于安全:二次打包链路完整走一遍
android·kotlin
墨天梦1 天前
D05_ViewModel与单向数据流
android·kotlin
墨天梦1 天前
D03_Compose列表与稳定身份
android·gitee·kotlin
萌新杰少1 天前
Kuikly股票查看软件开发体验——SaiRen
android·kotlin·客户端
用户92817267390161 天前
Android Compose版本的AI组件库来了。
android·kotlin
墨天梦2 天前
B19_SunnyWeather到阅读客户端
android·kotlin
墨天梦3 天前
B17_LifecycleLiveData与Flow
android·kotlin
熊猫钓鱼>_>3 天前
Kotlin Multiplatform for OpenHarmony 实战:为 Landscapist 实现图片加载适配
开发语言·kotlin·华为云·ai编程·harmonyos·鸿蒙·openharmony
ZealSinger4 天前
Kotlin2.4迁移context parameters
kotlin·协程·迁移·kotlin2.4