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

相关方法

相关推荐
赏金术士6 小时前
Kotlin 习题集 · 高级篇
android·开发语言·kotlin
问心无愧05138 小时前
ctf show web 入门42
android·前端·android studio
没什么本事9 小时前
关于C# panel 添加lable问题 -- 明确X和Y 位置错误
android·java·c#
REDcker13 小时前
Android HWASan 详解:硬件标记原理、Clang 启用与排障实践
android·linux·debug·编译·clang·asan·hwasan
2501_9159090613 小时前
全面解析前端开发中常用的浏览器调试工具及其使用场景
android·ios·小程序·https·uni-app·iphone·webview
angerdream13 小时前
Android手把手编写儿童手机远程监控App之SQLite详解2
android
-SOLO-13 小时前
Python 爬取小红书 文章标题和内容 仅供学习
android·python·学习
ooseabiscuit14 小时前
Laravel5
android·php·laravel
科技道人15 小时前
Android 禁止使用ipv6 测试
android·禁用ipv6
AlexMaybeBot15 小时前
巧用 OpenClaw 为 Android 开发电脑瘦身
android·github·ai编程