Represent closed, open, or half-open, bounded intervals in Kotlin and perform common operations on them. Values covered by the interval can be of a different type than distances between those values.
For example, IntInterval
has Int
values and UInt
distances:
val interval: IntInterval = interval( 0, 10, isEndIncluded = false )
val areIncluded = 0 in interval && 5 in interval // true
val areExcluded = 10 !in interval && 15 !in interval // true
val size: UInt = interval.size // 10
This protects against overflows (e.g. if size > Int.MAX_VALUE
) but also offers better semantics.
For example, this library supports kotlinx datetime Instant
values which are a Duration
apart.
val now = Clock.System.now()
val interval: InstantInterval = interval( now, now + 100.seconds )
val areIncluded = now + 50.seconds in interval // true
val size: Duration = interval.size // 100 seconds
This library includes a generic base class Interval<T, TSize>
which can be used to create intervals for any type.
To achieve this, it directs type operations to IntervalTypeOperations
which the constructor takes as a parameter.
The following interval types are included in io.github.whathecode.kotlinx.interval:kotlinx-interval
on Maven:
Type | Values (T ) |
Distances (TSize ) |
---|---|---|
ByteInterval |
Byte |
UByte |
ShortInterval |
Short |
UShort |
IntInterval |
Int |
UInt |
LongInterval |
Long |
ULong |
FloatInterval |
Float |
Double |
DoubleInterval |
Double |
Double |
UByteInterval |
UByte |
UByte |
UShortInterval |
UShort |
UShort |
UIntInterval |
UInt |
UInt |
ULongInterval |
ULong |
ULong |
CharInterval |
Char |
UShort |
Date/time intervals are implemented as InstantInterval
using the kotlinx datetime library.
Since you may not always want to pull in this dependency, this class is published separately in io.github.whathecode.kotlinx.interval:kotlinx-interval-datetime
.