Kotlin coerceAtMost用法及代码示例

本文方法及代码示例基于Kotlin 2.1.20 Released

coerceAtMost 所在包 kotlin.ranges.coerceAtMost,其相关用法介绍如下:

用法一

kotlin 复制代码
fun <T : Comparable<T>> T.coerceAtMost(maximumValue: T): T

确保此值不大于指定的 maximumValue

示例代码:

kotlin 复制代码
import java.time.DayOfWeek
import kotlin.test.assertFailsWith

fun main(args: Array<String>) {
    //sampleStart
    println(DayOfWeek.FRIDAY.coerceAtMost(DayOfWeek.SATURDAY)) // FRIDAY
    println(DayOfWeek.FRIDAY.coerceAtMost(DayOfWeek.WEDNESDAY)) // WEDNESDAY
    //sampleEnd
}

// 输出
FRIDAY
WEDNESDAY

如果它小于或等于maximumValue,则返回此值,否则返回maximumValue

用法二

kotlin 复制代码
fun Byte.coerceAtMost(maximumValue: Byte): Byte

fun Short.coerceAtMost(maximumValue: Short): Short

fun Int.coerceAtMost(maximumValue: Int): Int

fun Long.coerceAtMost(maximumValue: Long): Long

fun Float.coerceAtMost(maximumValue: Float): Float

fun Double.coerceAtMost(maximumValue: Double): Double

确保此值不大于指定的 maximumValue

示例代码:

kotlin 复制代码
import java.time.DayOfWeek
import kotlin.test.assertFailsWith

fun main(args: Array<String>) {
    //sampleStart
    println(10.coerceAtMost(5)) // 5
    println(10.coerceAtMost(20)) // 10
    //sampleEnd
}

// 输出
5
10

如果它小于或等于maximumValue,则返回此值,否则返回maximumValue

用法三

kotlin 复制代码
fun UInt.coerceAtMost(maximumValue: UInt): UInt

fun ULong.coerceAtMost(maximumValue: ULong): ULong

fun UByte.coerceAtMost(maximumValue: UByte): UByte

fun UShort.coerceAtMost(maximumValue: UShort): UShort

确保此值不大于指定的 maximumValue

代码示例:

kotlin 复制代码
import java.time.DayOfWeek
import kotlin.test.assertFailsWith

fun main(args: Array<String>) {
    //sampleStart
    println(10u.coerceAtMost(5u)) // 5
    println(10u.coerceAtMost(20u)) // 10
    //sampleEnd
}

// 输出
5
10

如果它小于或等于maximumValue,则返回此值,否则返回maximumValue

相关方法

相关推荐
kymjs张涛2 小时前
零一开源|前沿技术周报 #7
android·前端·ios
wuwu_q3 小时前
RK3566/RK3568 Android11 修改selinux模式
android·rk3568
_一条咸鱼_4 小时前
Android Runtime内存共享与访问控制原理剖析(71)
android·面试·android jetpack
嘉小华4 小时前
第三章:焦点分发全链路源码解析
android
嘉小华4 小时前
Android 协程全景式深度解析:第六章 高阶并发模式
android
嘉小华4 小时前
Android 协程全景式深度解析:第七章 协程调试与性能优化
android
你过来啊你4 小时前
Android开发中RxJava的使用与原理
android
你过来啊你5 小时前
Android Glide使用与底层机制详解
android
血舞之境5 小时前
Android 模块打包成aar遇到的空指针的问题
android
嘉小华5 小时前
Android 协程全景式深度解析:第四章 Flow响应式流
android·前端