Library contents

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

  1. Start with 8, allowed range 1–5
  2. Do this Keep the value inside the range
  3. Result 5
Eight exceeds the upper limit, so the result is the upper limit.
Lesson.kt
fun main() {
    println(8.coerceIn(1, 5))
}
Output
5

Syntax

Kotlin 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.

First output line0
Lesson.kt
fun main() {
    for (value in listOf(-5, 42, 130)) {
        println(value.coerceIn(0, 100))
    }
}
Output
0
42
100

Both endpoints are allowed. Reversing the bounds raises IllegalArgumentException, so validate externally supplied limits before applying them.

Kotlin documentation for coerceIn

Advertisements

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.

GivenRequested 4 · range 10–90
Worked result10

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.

GivenRequested 5 · range 1–8
Worked result5

A request inside the permitted interval passes through.