data class OpenFloatRange(val from: Float, val to: Float)
infix fun Float.open(to: Float) = OpenFloatRange(this, to)
operator fun OpenFloatRange.contains(f: Float) = from < f && f < to
val inRange = 10f in (0.0f open 20f)
class Range(private val fromInclusive: Boolean, val from: Float, val to: Float, private val toInclusive: Boolean) {
infix fun contains(value: Float): Boolean {
return when {
fromInclusive && toInclusive -> value in from..to
!fromInclusive && !toInclusive -> value > from && value < to
!fromInclusive && toInclusive -> value > from && value <= to
fromInclusive && !toInclusive -> value >= from && value < to
else -> false
}
}
}
kotlin {
jvm {
compilations.all {
kotlinOptions.languageVersion = "1.8" // Treat Kotlin code as version 1.8
// ...
}
它开启了until无法实现的可能性:
val floatRange = 0f ..< 10f
val dateRange = LocalDate.of(2022, 1, 1) ..< LocalDate.of(2023, 1, 1)
val stringRange = "1z" ..< "9a"
// OR anything implementing Comparable
when (7.89f) {
in floatRange -> println("Number is in range")
else -> println("Number is NOT in range")
}
3条答案
按热度按时间yquaqz181#
until
函数创建半封闭整数(非浮点型)范围,其中包括左半部分,不包括右半部分。https://kotlinlang.org/docs/reference/ranges.html在Koltin www.example.com中有封闭浮点范围支持https://kotlinlang.org/docs/reference/ranges.html#utility-functions
您可以自己实现
在这里,我使用了Kotlin的几个技巧:https://kotlinlang.org/docs/reference/functions.html#infix-notationhttps://kotlinlang.org/docs/reference/operator-overloading.html#in
798qvoo82#
受到我选择的答案的启发,我想出了这个解决方案,如果有人想重用它,就把它贴在这里。
用法:
val inRange = Range(true, 0f, 10f, false) contains 5f
uemypmqf3#
有一个新的结束封闭运算符**
..<
(称为rangeUntil),它仍处于实验阶段,可以在Kotlin1.7.20
**和更新版本中启用。在 build.gradle.kts 中添加以下内容(Kotlin
1.8
不需要此内容):它开启了
until
无法实现的可能性:注意:请记住在使用此运算符的函数中添加
@OptIn(ExperimentalStdlibApi::class)
请参阅official Kotlin video introducing the
rangeUntil
operator。