当前位置: 首页 > ds >正文

Kotlin 边界限制

文章目录

  • Kotlin 边界限制
    • 传统方式
    • coerceIn
    • coerceAtLeast
    • coerceAtMost
    • 自定义类型

Kotlin 边界限制

传统方式

fun processScore(score: Int): Int {if (score < 0) {return 0} else if (score > 100) {return 100}return score
}println(processScore(-10)) // 0
println(processScore(80)) // 80
println(processScore(120)) // 100

coerceIn

coerceIn():限制值的范围,超出范围则返回边界值。

fun processScore2(score: Int): Int {return score.coerceIn(0, 100)
}println(processScore2(-10)) // 0
println(processScore2(80)) // 80
println(processScore2(120)) // 100

coerceAtLeast

coerceAtLeast():限制下限,低于下限值则返回下限值。

fun processScore3(score: Int): Int {return score.coerceAtLeast(0)
}println(processScore3(-10)) // 0
println(processScore3(80)) // 80
println(processScore3(120)) // 120

coerceAtMost

coerceAtMost():限制上限,高于上限值则返回上限值。

fun processScore4(score: Int): Int {return score.coerceAtMost(100)
}println(processScore4(-10)) // -10
println(processScore4(80)) // 80
println(processScore4(120)) // 100

自定义类型

// 自定义Comparable类
data class MyDate(val year: Int, val month: Int, val day: Int) : Comparable<MyDate> {override fun compareTo(other: MyDate): Int {return compareValuesBy(this, other,{ it.year }, { it.month }, { it.day })}
}// 定义扩展函数
fun <T : Comparable<T>> T.coerceIn(min: T, max: T): T {if (this < min) {return min} else if (this > max) {return max}return this
}fun processDate(date: MyDate): MyDate {val minDate = MyDate(2024, 1, 1)val maxDate = MyDate(2024, 12, 31)return date.coerceIn(minDate, maxDate)
}val date = MyDate(2023, 2, 30)
println(processDate(date)) // MyDate(year=2024, month=1, day=1)
val date2 = MyDate(2024, 1, 1)
println(processDate(date2)) // MyDate(year=2024, month=1, day=1)
val date3 = MyDate(2025, 1, 1)
println(processDate(date3)) // MyDate(year=2024, month=12, day=31)
http://www.xdnf.cn/news/1394.html

相关文章:

  • 加油站小程序实战教程14会员充值页面搭建
  • centos stream 10 修改 metric
  • python——模块、包、操作文件
  • 网络原理 - 5(TCP - 2 - 三次握手与四次挥手)
  • 深度解析n8n全自动AI视频生成与发布工作流
  • 多 Agent 系统开发指南:分布式协同、通信机制与性能优化
  • Unity ML-Agents + VScode 环境搭建 Windows
  • Manim让数学动画更有温度
  • windows怎样生成iOS证书-uniapp打包
  • RK3568平台开发系列讲解(调试篇)debugfs文件系统及常见调试节点介绍
  • 基于HPC的气候模拟GPU加速实践全流程解析
  • 【架构】Armstrong公理系统通俗详解:数据库设计的基本法则
  • 【Canvas与标志】红底肉边黑芯铁十字标志
  • socket编程基础
  • MongoDB Ubuntu 安装
  • 大数据利器:Kafka与Spark的深度探索
  • JAVA设计模式——(四)门面模式
  • 大模型驱动金融数据应用的实战探索
  • 网络安全职业技能大赛Server2003
  • 使用 Oracle 数据库进行基于 JSON 的应用程序开发
  • 线程概念与控制
  • (四)微服务架构、容器编排架构
  • CPP_类和对象
  • 安全复健|windows常见取证工具
  • 基于Java与MAVLink协议的多无人机(Cube飞控)集群控制与调度方案问题
  • 如何开启远程桌面连接外网访问?异地远程控制内网主机
  • GitLab Runner配置并行执行多个任务
  • 路由与OSPF学习
  • DeepSeek在物联网设备中的应用:通过轻量化模型实现本地化数据分析
  • setInterval可能的坑