Kotlin coerceIn
coerceIn returns the receiver when it is inside a closed range, or the nearest endpoint when it falls outside.
A simple example
coerceIn
- Start with 8, allowed range 1–5
- Do this Keep the value inside the range
- Result 5
fun main() {
println(8.coerceIn(1, 5))
}
5
Syntax
value.coerceIn(minimum, maximum)
Run this example in Kotlin
Save the program as Lesson.kt. Use Kotlin 2.2 on the JVM.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Clamp a requested brightness to its allowed range
A brightness control accepts settings within a fixed display range. Bring a request outside either end back to the appropriate boundary before sending it to the device.
fun main() {
for (value in listOf(-5, 42, 130)) {
println(value.coerceIn(0, 100))
}
}
0 42 100
Both endpoints are allowed. Reversing the bounds raises IllegalArgumentException, so validate externally supplied limits before applying them.
Kotlin documentation for coerceIn
Set a reading lamp’s brightness
A classroom lamp accepts an intensity from 10 to 90. A saved preference of 4 falls below the allowed interval.
The lower bound becomes the setting when the request is below the range.
Keep a valid camera zoom
A camera interface allows a zoom level between one and eight. A photographer recalls level five from a preset.
A request inside the permitted interval passes through.