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

相关方法

相关推荐
爱学习的大牛1231 小时前
使用C++开发Android .so库的优势与实践指南
android·.so·1024程序员节
太过平凡的小蚂蚁2 小时前
Kotlin 协程中常见的异步返回与控制方式(速览)
开发语言·前端·kotlin
帅锅锅0074 小时前
SeLinux Type(类型)深度解析
android·操作系统
2501_915921434 小时前
iOS混淆与IPA加固全流程(iOS混淆 IPA加固 Ipa Guard实战)
android·ios·小程序·https·uni-app·iphone·webview
游戏开发爱好者84 小时前
iOS 26 App 开发阶段性能优化 从多工具协作到数据驱动的实战体系
android·ios·小程序·uni-app·iphone·webview·1024程序员节
2501_915106325 小时前
深入剖析 iOS 26 系统流畅度,多工具协同监控与性能优化实践
android·ios·性能优化·小程序·uni-app·cocoa·iphone
小彤花园5 小时前
GooglePlay更改签名秘钥报错(2025最新版)
android·google
Answer_momo6 小时前
一文读懂 Kotlin 数据流 Flow 的使用
android
雨白6 小时前
Kotlin Flow 入门:构建响应式异步数据流
android·kotlin