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():限制值的范围,超出范围则返回边界值。

fun processScore2(score: Int): Int {
    return score.coerceIn(0, 100)
}

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

coerceAtLeast

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

fun processScore3(score: Int): Int {
    return score.coerceAtLeast(0)
}

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

coerceAtMost

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

fun processScore4(score: Int): Int {
    return score.coerceAtMost(100)
}

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

自定义类型

// 自定义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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值