Skip to content

Commit

Permalink
Use base type "Number" as constructor parameter for easier instantiat…
Browse files Browse the repository at this point in the history
…ion of Interval class.
  • Loading branch information
kizitonwose committed Oct 31, 2017
1 parent 2062f83 commit c286d2b
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions time/src/main/kotlin/com/kizitonwose/time/Time.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,17 @@ interface TimeUnit {
}


class Interval<out T : TimeUnit>(val value: Double, val factory: () -> T) {
class Interval<out T : TimeUnit>(value: Number, val factory: () -> T) {

companion object {
inline operator fun <reified K : TimeUnit> invoke(value: Number) = Interval(value) {
K::class.java.newInstance()
}
}

val value = value.toDouble()

val longValue = Math.round(this.value)

val inDays: Interval<Day>
get() = converted()
Expand All @@ -36,19 +46,12 @@ class Interval<out T : TimeUnit>(val value: Double, val factory: () -> T) {
val inNanoseconds: Interval<Nanosecond>
get() = converted()

val longValue = Math.round(value)

inline fun <reified OtherUnit : TimeUnit> converted(): Interval<OtherUnit> {
val otherInstance = OtherUnit::class.java.newInstance()
return Interval(value * factory().conversionRate(otherInstance))
}

companion object {
inline operator fun <reified K : TimeUnit> invoke(value: Double) = Interval(value) {
K::class.java.newInstance()
}
}

operator fun plus(other: Interval<TimeUnit>): Interval<T> {
val newValue = value + other.value * other.factory().conversionRate(factory())
return Interval(newValue) { factory() }
Expand Down Expand Up @@ -116,25 +119,25 @@ class Nanosecond : TimeUnit {


val Number.days: Interval<Day>
get() = Interval(this.toDouble())
get() = Interval(this)

val Number.hours: Interval<Hour>
get() = Interval(this.toDouble())
get() = Interval(this)

val Number.minutes: Interval<Minute>
get() = Interval(this.toDouble())
get() = Interval(this)

val Number.seconds: Interval<Second>
get() = Interval(this.toDouble())
get() = Interval(this)

val Number.milliseconds: Interval<Millisecond>
get() = Interval(this.toDouble())
get() = Interval(this)

val Number.microseconds: Interval<Microsecond>
get() = Interval(this.toDouble())
get() = Interval(this)

val Number.nanoseconds: Interval<Nanosecond>
get() = Interval(this.toDouble())
get() = Interval(this)



0 comments on commit c286d2b

Please sign in to comment.