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。

相关方法

相关推荐
weixin_394758038 小时前
CRMEB Pro 优惠券:下单怎么核销,取消/退款怎么返券
android
alexhilton9 小时前
Android 17 内存预算成为必修课
android·kotlin·android jetpack
AI2中文网11 小时前
App Inventor 对接 OneNet:手机收数据
android·鸿蒙·app inventor
好的佩奇12 小时前
Dart 之文件读写
android·flutter·dart
砚底藏山河14 小时前
量化行情横截面中性化闭式与回归实现
android·java·python·金融·kotlin
明君68914 小时前
APK 签名绕过方案(Android 10~17)
android
芝麻别开门14 小时前
Android libmpv 源码下载与编译
android·mpv·libmpv
FLJwu14 小时前
运动相机代工模具风控③:试模样品、结构公差、装配干涉,提前规避大货装配不良
android·开发语言·数码相机·运动相机·oem 量产
应用市场15 小时前
安卓底层拆解(四)· 属性要成套:abilist 与 zygote 的连锁反应
android·zygote
齊家治國平天下16 小时前
Android Automotive(AAOS)系统入门:从五层架构到车载机制
android·架构·车载系统·aaos·智能座舱