Kotlin coerceAtMost用法及代码示例

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

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

用法一

kotlin 复制代码
fun <T : Comparable<T>> T.coerceAtMost(maximumValue: T): T

确保此值不大于指定的 maximumValue

示例代码:

kotlin 复制代码
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

用法二

kotlin 复制代码
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

示例代码:

kotlin 复制代码
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

用法三

kotlin 复制代码
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

代码示例:

kotlin 复制代码
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

相关方法

相关推荐
Mac的实验室13 分钟前
2026年最新真实社交怎么注册?手把手教你如何成功注册Truth Social账号
android
毕设源码-郭学长1 小时前
【开题答辩全过程】以 基于Android的点餐APP的设计为例,包含答辩的问题和答案
android
polaris06301 小时前
学生成绩管理系统(MySQL)
android·数据库·mysql
__Yvan1 小时前
Kotlin 的 ?.let{} ?: run{} 真的等价于 if-else 吗?
android·开发语言·前端·kotlin
tangweiguo030519871 小时前
Android WorkManager 完整实战教程(含完整文件)
android·kotlin
loitawu2 小时前
Rockchip Android16 系统裁剪指南
android·android16·android裁剪·系统裁剪·rockchip app
小羊子说3 小时前
关于车机中的升级流程小结(SOC、MCU、4G升级流程)
android·adb·性能优化·车载系统
肖。35487870943 小时前
[技巧-11]AndroidManifest.xml完善小技巧。
android
小羊子说3 小时前
Android 车机开发中常用的adb 脚本(更新中)
android·linux·adb·性能优化·车载系统
用户7607495397834 小时前
Android页面四大布局运行结果
android