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

相关方法

相关推荐
zh_xuan4 小时前
Android Hilt实现依赖注入
android·hilt
freshman_y4 小时前
Qtcreator怎么新建安卓项目?编写一个五子棋游戏APP?
android·qt
时寒的笔记5 小时前
js逆向7_案例惠nong网
android·开发语言·javascript
雨白5 小时前
深入理解 Kotlin 协程 (三):返璞归真,探寻协程基础设施的底层基石
kotlin
肯多洛夫斯基6 小时前
安卓工控屏静默连WiFi全攻略
android
极梦网络无忧6 小时前
Android无障碍服务实现抖音直播间界面监控(场控助手核心原理)
android
call me by ur name7 小时前
ERNIE 5.0 Technical Report论文解读
android·开发语言·人工智能·机器学习·ai·kotlin
kerli8 小时前
Compose 组件:Box 核心参数及其 Bias 算法
android·前端
BLUcoding8 小时前
Android 常用控件及核心属性
android
遥不可及zzz8 小时前
[特殊字符] Android AAB 一键安装工具配置指南
android·macos