Provide ComparableRange specializations for Double and Float.

#KT-4481
This commit is contained in:
Ilya Gorbunov
2016-11-03 23:34:48 +03:00
parent 1aad82bbaf
commit f5cc53c157
2 changed files with 39 additions and 2 deletions
+24 -2
View File
@@ -5,7 +5,7 @@ package kotlin.ranges
/**
* Represents a range of [Comparable] values.
*/
private class ComparableRange<T: Comparable<T>> (
private open class ComparableRange<T: Comparable<T>> (
override val start: T,
override val endInclusive: T
): ClosedRange<T> {
@@ -22,11 +22,33 @@ private class ComparableRange<T: Comparable<T>> (
override fun toString(): String = "$start..$endInclusive"
}
private class DoubleRange (
start: Double,
endInclusive: Double
): ComparableRange<Double>(start, endInclusive) {
override fun contains(value: Double): Boolean = value >= start && value <= endInclusive
override fun isEmpty(): Boolean = start > endInclusive
}
private class FloatRange (
start: Float,
endInclusive: Float
): ComparableRange<Float>(start, endInclusive) {
override fun contains(value: Float): Boolean = value >= start && value <= endInclusive
override fun isEmpty(): Boolean = start > endInclusive
}
/**
* Creates a range from this [Comparable] value to the specified [that] value. This value
* needs to be smaller than [that] value, otherwise the returned range will be empty.
*/
public operator fun <T: Comparable<T>> T.rangeTo(that: T): ClosedRange<T> = ComparableRange(this, that)
public operator fun <T: Comparable<T>> T.rangeTo(that: T): ClosedRange<T> =
@Suppress("UNCHECKED_CAST")
when {
this is Double && that is Double -> DoubleRange(this, that) as ClosedRange<T>
this is Float && that is Float -> FloatRange(this, that) as ClosedRange<T>
else -> ComparableRange(this, that)
}
internal fun checkStepIsPositive(isPositive: Boolean, step: Number) {