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

相关方法

相关推荐
志存高远661 小时前
(面试)Android各版本新特性
android
IT从业者张某某2 小时前
信奥赛-刷题笔记-队列篇-T3-P3662Why Did the Cow Cross the Road II S
android·笔记
未来之窗软件服务2 小时前
Cacti 未经身份验证SQL注入漏洞
android·数据库·sql·服务器安全
BXCQ_xuan2 小时前
handsome主题美化及优化:10.1.0最新版 - 2
android
圈圈编码2 小时前
MVVM框架
android·学习·kotlin
橙子199110164 小时前
在 Kotlin 中,什么是解构,如何使用?
android·开发语言·kotlin
androidwork5 小时前
Android 中使用通知(Kotlin 版)
android·kotlin
Digitally6 小时前
如何从 Android 设备打印短信(5 种方法)
android
casual_clover6 小时前
Android 中 打开文件选择器(ACTION_OPEN_DOCUMENT )
android
_龙小鱼_7 小时前
卡顿检测与 Choreographer 原理
android·kotlin