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)
}
相关推荐
Kapaseker7 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
A0微声z2 天前
Kotlin Multiplatform (KMP) 中使用 Protobuf
kotlin
alexhilton3 天前
使用FunctionGemma进行设备端函数调用
android·kotlin·android jetpack
lhDream3 天前
Kotlin 开发者必看!JetBrains 开源 LLM 框架 Koog 快速上手指南(含示例)
kotlin
RdoZam3 天前
Android-封装基类Activity\Fragment,从0到1记录
android·kotlin
Kapaseker3 天前
研究表明,开发者对Kotlin集合的了解不到 20%
android·kotlin
糖猫猫cc4 天前
Kite:两种方式实现动态表名
java·kotlin·orm·kite
如此风景4 天前
kotlin协程学习小计
android·kotlin
Kapaseker4 天前
你搞得懂这 15 个 Android 架构问题吗
android·kotlin
zh_xuan4 天前
kotlin 高阶函数用法
开发语言·kotlin