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)
}
相关推荐
太过平凡的小蚂蚁6 小时前
Kotlin 协程中常见的异步返回与控制方式(速览)
开发语言·前端·kotlin
雨白10 小时前
Kotlin Flow 入门:构建响应式异步数据流
android·kotlin
shayudiandian11 小时前
【Kotlin】数组集合常用扩展函数
kotlin
I'm Jie1 天前
(五)Gradle 依赖传递与冲突处理
java·spring boot·spring·kotlin·gradle·maven
消失的旧时光-19431 天前
Kotlin 高阶函数在回调设计中的最佳实践
android·开发语言·kotlin
用户092 天前
Kotlin Flow的6个必知高阶技巧
android·面试·kotlin
用户092 天前
Jetpack Compose静态与动态CompositionLocal深度解析
android·面试·kotlin
Jeled2 天前
「高级 Android 架构师成长路线」的第 1 阶段 —— 强化体系与架构思维(Clean Architecture 实战)
android·kotlin·android studio·1024程序员节
明道源码2 天前
Kotlin 控制流、函数、Lambda、高阶函数
android·开发语言·kotlin
橙子199110162 天前
在 Kotlin 中,ViewModel 的获取
开发语言·vue.js·kotlin