In Kotlin, is there an idiomatic way to test if a float is in a range where either (or both) the start or the end of the range is exclusive?
E.g. something like
val inRange = 10.f in (0.0f until 20f)
I can't seem to find anything on this in the docs.
How would one deal with semi-open ranges as well?
The until
function creates the semi-closed integer (not float) range, where the left part is included and the right part is excluded.
https://kotlinlang.org/docs/reference/ranges.html
There is closed float ranges support in Koltin https://kotlinlang.org/docs/reference/ranges.html#utility-functions
You may implement that yourself
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)
Here I use several tricks from Kotlin: https://kotlinlang.org/docs/reference/functions.html#infix-notation https://kotlinlang.org/docs/reference/operator-overloading.html#in
Inspired by what i selected as answer i came up with this solution, posting it here if anyone wants to reuse it.
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
}
}
}
Usage: val inRange = Range(true, 0f, 10f, false) contains 5f
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With