Kotlin coerceAtLeast用法及代码示例

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

coerceAtLeast所在位置是kotlin.ranges.coerceAtLeast,其相关用法介绍如下。

用法一

kotlin 复制代码
fun <T : Comparable<T>> T.coerceAtLeast(minimumValue: T): T

确保此值不小于指定的 minimumValue

代码示例:

kotlin 复制代码
import java.time.DayOfWeek
import kotlin.test.assertFailsWith

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

// 输出
WEDNESDAY
FRIDAY

如果它大于或等于minimumValue,则返回此值,否则返回minimumValue

用法二

kotlin 复制代码
fun Byte.coerceAtLeast(minimumValue: Byte): Byte

fun Short.coerceAtLeast(minimumValue: Short): Short

fun Int.coerceAtLeast(minimumValue: Int): Int

fun Long.coerceAtLeast(minimumValue: Long): Long

fun Float.coerceAtLeast(minimumValue: Float): Float

fun Double.coerceAtLeast(minimumValue: Double): Double

确保此值不小于指定的 minimumValue

代码示例:

kotion 复制代码
import java.time.DayOfWeek
import kotlin.test.assertFailsWith

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

// 输出
10
20

如果它大于或等于minimumValue,则返回此值,否则返回minimumValue

用法三

kotlin 复制代码
fun UInt.coerceAtLeast(minimumValue: UInt): UInt

fun ULong.coerceAtLeast(minimumValue: ULong): ULong

fun UByte.coerceAtLeast(minimumValue: UByte): UByte

fun UShort.coerceAtLeast(minimumValue: UShort): UShort

确保此值不小于指定的 minimumValue

代码示例:

kotlin 复制代码
import java.time.DayOfWeek
import kotlin.test.assertFailsWith

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

// 输出
10
20

如果它大于或等于minimumValue,则返回此值,否则返回minimumValue

相关方法

相关推荐
程序员煊子4 小时前
用 Cursor 从零搭一个 Compose 本地记账 App:实战记录与源码解析
android·kotlin·compose·cursor
alexhilton6 小时前
面向Android开发者的Google I/O 2026
android·kotlin·android jetpack
私人珍藏库6 小时前
【Android】豆图助手-永久HY-模拟微X~zfb各种截图
android·app·工具·软件·多功能
程序员陆业聪7 小时前
Shadow实战接入与生产落地:从零搭建到稳定运行
android
程序员陆业聪7 小时前
Shadow Transform:编译期的魔法——字节码替换实战
android
imuliuliang11 小时前
Laravel6.x核心特性全解析
android·php·laravel
idingzhi12 小时前
A股量化策略日报(2026年05月22日)
android·开发语言·python·kotlin
测试员周周13 小时前
【Appium 系列】第14节-断言与验证 — Validator 的设计
android·人工智能·python·功能测试·ios·单元测试·appium
赏金术士14 小时前
Android 动画对比指南:View 系统 vs Jetpack Compose
android·kotlin·compose
爱写代码的小任14 小时前
Hermes Agent 源码解析(三):Agent 主循环 —— run_agent.py 的核心秘密
源码阅读