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

相关方法

相关推荐
xxjj998a15 分钟前
Laravel 1.x:PHP框架的原始魅力
android·php·laravel
formula1000016 分钟前
在iOS/安卓上远程连接任何 Agent!Claude、Codex、Copilot、Gemini、OpenCode 等
android·copilot
该用户可能存在37 分钟前
Blbl-android 更新至 v0.1.24,体验更流畅、更稳定
android·哔哩哔哩·电视app·androidtv·bbll·blbl·bilibilitv
lKWO OMET1 小时前
mysql之字符串函数
android·数据库·mysql
liang_jy11 小时前
Android SparseArray
android·源码
liang_jy12 小时前
Activity 启动流程扩展篇(一)—— startActivityInner 任务决策全解析
android·源码
NPE~13 小时前
[App逆向]脱壳实战
android·教程·逆向·android逆向·逆向分析
木易 士心13 小时前
别再只会用 drawCircle 了!一文搞懂 Android Canvas 底层机制
android
AtOR CUES14 小时前
MySQL——表操作及查询
android·mysql·adb
怣疯knight16 小时前
安卓App无法增加自定义图片作为图标功能
android