clamp

fun Int.clamp(min: Int, max: Int): Int

Constrains this value to be within a specified range.

If the value is less than the minimum (min), it returns min. If the value is greater than the maximum (max), it returns max. Otherwise, it returns the original value.

Example:

val value = 15
val clampedValue = value.clamp(0, 10) // clampedValue will be 10

val anotherValue = 5
val anotherClamped = anotherValue.clamp(0, 10) // anotherClamped will be 5

Return

The value constrained to the min, max range.

Parameters

min

The minimum value of the range (inclusive).

max

The maximum value of the range (inclusive).


fun Float.clamp(min: Float, max: Float): Float

Clamps this value to be within the specified range.

If this value is less than the minimum value min, it returns min. If this value is greater than the maximum value max, it returns max. Otherwise, it returns this value itself.

This ensures the returned value is always between min and max (inclusive).

Example:

val value = 150
val clampedValue = value.clamp(0, 100) // clampedValue will be 100

val anotherValue = -10
val anotherClamped = anotherValue.clamp(0, 100) // anotherClamped will be 0

val inRangeValue = 50
val inRangeClamped = inRangeValue.clamp(0, 100) // inRangeClamped will be 50

Return

The clamped value, which is guaranteed to be in the range `min`, `max`.

Parameters

min

The minimum value of the range.

max

The maximum value of the range.