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 double-open floating point range yourself:
data class OpenFloatingPointRange(
val startExclusive: Double,
val endExclusive: Double,
)
infix fun Double.untilOpen(endExclusive: Double) = OpenFloatingPointRange(
startExclusive = this,
endExclusive = endExclusive,
)
operator fun OpenFloatingPointRange.contains(
value: Double,
) = startExclusive < value && value < endExclusive
val ClosedFloatingPointRange<Double>.open: OpenFloatingPointRange
get() = OpenFloatingPointRange(
startExclusive = this.start,
endExclusive = this.endInclusive,
)
val inRange = 10.0 in (0.0 untilOpen 20.0)
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