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

相关方法

相关推荐
2501_915918411 小时前
iOS 26 App 性能测试|性能评测|iOS 26 性能对比:实战策略
android·macos·ios·小程序·uni-app·cocoa·iphone
咋吃都不胖lyh5 小时前
SQL-多对多关系
android·mysql·数据分析
cyy2985 小时前
android 屏幕适配
android
Digitally7 小时前
如何通过 5 种有效方法同步 Android 和 Mac
android·macos
爱学啊8 小时前
3.Android Compose 基础系列:在 Kotlin 中创建和使用函数
kotlin·compose·android compose开发基础
行墨8 小时前
Jetpack Compose 深入浅出(二)——基础组件Text
android
低调小一10 小时前
LRU缓存科普与实现(Kotlin 与 Swift)
开发语言·缓存·kotlin
雨白10 小时前
深入理解协程的运作机制 —— 调度、挂起与性能
android·kotlin
沐怡旸10 小时前
【Android】Android系统体系结构
android
namehu11 小时前
React Native 应用性能分析与优化不完全指南
android·react native·ios