W3cubDocs

/Kotlin

coerceAtMost

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
fun <T : Comparable<T>> T.coerceAtMost(maximumValue: T): T

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

import java.time.DayOfWeek
import kotlin.test.assertFailsWith

fun main(args: Array<String>) {
//sampleStart
println(DayOfWeek.FRIDAY.coerceAtMost(DayOfWeek.SATURDAY)) // FRIDAY
println(DayOfWeek.FRIDAY.coerceAtMost(DayOfWeek.WEDNESDAY)) // WEDNESDAY
//sampleEnd
}

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

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
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.

import java.time.DayOfWeek
import kotlin.test.assertFailsWith

fun main(args: Array<String>) {
//sampleStart
println(10.coerceAtMost(5)) // 5
println(10.coerceAtMost(20)) // 10
//sampleEnd
}

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

Platform and version requirements: JVM (1.3), JS (1.3), Native (1.3)
@ExperimentalUnsignedTypes fun UInt.coerceAtMost(
    maximumValue: UInt
): UInt
@ExperimentalUnsignedTypes fun ULong.coerceAtMost(
    maximumValue: ULong
): ULong
@ExperimentalUnsignedTypes fun UByte.coerceAtMost(
    maximumValue: UByte
): UByte
@ExperimentalUnsignedTypes fun UShort.coerceAtMost(
    maximumValue: UShort
): UShort

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

import java.time.DayOfWeek
import kotlin.test.assertFailsWith

fun main(args: Array<String>) {
//sampleStart
println(10u.coerceAtMost(5u)) // 5
println(10u.coerceAtMost(20u)) // 10
//sampleEnd
}

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

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/coerce-at-most.html