Kotlin coerceAtMost用法及代码示例

165 阅读1分钟

本文方法及代码示例基于 Kotlin 2.1.20 Released

coerceAtMost 所在包 kotlin.ranges.coerceAtMost,其相关用法介绍如下:

用法一

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

确保此值不大于指定的 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
}

// 输出
FRIDAY
WEDNESDAY

如果它小于或等于maximumValue,则返回此值,否则返回maximumValue

用法二

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

确保此值不大于指定的 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
}

// 输出
5
10

如果它小于或等于maximumValue,则返回此值,否则返回maximumValue

用法三

fun UInt.coerceAtMost(maximumValue: UInt): UInt

fun ULong.coerceAtMost(maximumValue: ULong): ULong

fun UByte.coerceAtMost(maximumValue: UByte): UByte

fun UShort.coerceAtMost(maximumValue: UShort): UShort

确保此值不大于指定的 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
}

// 输出
5
10

如果它小于或等于maximumValue,则返回此值,否则返回maximumValue

相关方法