coerceAtMost

fun <T : Comparable<T>> T.coerceAtMost(maximumValue: T): T

Ensures that this value is not greater than the specified maximumValue.

Return

this value if it's less than or equal to the maximumValue or the maximumValue otherwise.

Samples

import samples.*
import java.time.DayOfWeek
import kotlin.test.assertFailsWith
fun main() { 
   //sampleStart 
   assertPrints(DayOfWeek.FRIDAY.coerceAtMost(DayOfWeek.SATURDAY), "FRIDAY")
assertPrints(DayOfWeek.FRIDAY.coerceAtMost(DayOfWeek.WEDNESDAY), "WEDNESDAY") 
   //sampleEnd
}

fun Byte.coerceAtMost(maximumValue: Byte): Byte
fun Short.coerceAtMost(maximumValue: Short): Short
fun Int.coerceAtMost(maximumValue: Int): Int
fun Long.coerceAtMost(maximumValue: Long): Long
fun Float.coerceAtMost(maximumValue: Float): Float
fun Double.coerceAtMost(maximumValue: Double): Double

Ensures that this value is not greater than the specified maximumValue.

Return

this value if it's less than or equal to the maximumValue or the maximumValue otherwise.

Samples

import samples.*
import java.time.DayOfWeek
import kotlin.test.assertFailsWith
fun main() { 
   //sampleStart 
   assertPrints(10.coerceAtMost(5), "5")
assertPrints(10.coerceAtMost(20), "10") 
   //sampleEnd
}

fun UInt.coerceAtMost(maximumValue: UInt): UInt
fun ULong.coerceAtMost(maximumValue: ULong): ULong
fun UByte.coerceAtMost(maximumValue: UByte): UByte
fun UShort.coerceAtMost(maximumValue: UShort): UShort

Ensures that this value is not greater than the specified maximumValue.

Return

this value if it's less than or equal to the maximumValue or the maximumValue otherwise.

Since Kotlin

1.5

Samples

import samples.*
import java.time.DayOfWeek
import kotlin.test.assertFailsWith
fun main() { 
   //sampleStart 
   assertPrints(10u.coerceAtMost(5u), "5")
assertPrints(10u.coerceAtMost(20u), "10") 
   //sampleEnd
}