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)
}
相关推荐
千码君20161 小时前
kotlin:jetpack compose 生成动态可控的动画
vue.js·elementui·kotlin
alexhilton18 小时前
Jetpack Compose元球边缘效果
android·kotlin·android jetpack
Kiri霧1 天前
Kotlin递归
android·开发语言·kotlin
普通网友1 天前
Android开发:使用Kotlin+协程+自定义注解+Retrofit的网络框架
android·kotlin·retrofit
常利兵1 天前
Kotlin抽象类与接口:相爱相杀的编程“CP”
android·开发语言·kotlin
Arkerman_Liwei1 天前
Android 新开发模式深度实践:Kotlin + 协程 + Flow+MVVM
android·开发语言·kotlin
蹦哒1 天前
Kotlin DSL 风格编程详解
android·开发语言·kotlin
JJay.1 天前
Kotlin 高阶函数学习指南
android·开发语言·kotlin
android_cai_niao1 天前
kotlin中的when
kotlin·when
渔舟小调1 天前
后端框架选型:为什么选Kotlin + Spring Boot
kotlin·idea