一、概念
當需要對數值進行范圍限制時,通常會用 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 確保值不大于指定最大值,大于則返回最大值。 |
fun demo(age: Int) {val safeAge = age.corceIn(0, 130)
}
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)
}