From c286d2bd9a8b3358ba20407b1e9242e9a7dfc68b Mon Sep 17 00:00:00 2001 From: Kizito Nwose Date: Tue, 31 Oct 2017 09:47:07 +0100 Subject: [PATCH] Use base type "Number" as constructor parameter for easier instantiation of Interval class. --- .../main/kotlin/com/kizitonwose/time/Time.kt | 33 ++++++++++--------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/time/src/main/kotlin/com/kizitonwose/time/Time.kt b/time/src/main/kotlin/com/kizitonwose/time/Time.kt index 4dd5bc0..5e3b9dd 100644 --- a/time/src/main/kotlin/com/kizitonwose/time/Time.kt +++ b/time/src/main/kotlin/com/kizitonwose/time/Time.kt @@ -13,7 +13,17 @@ interface TimeUnit { } -class Interval(val value: Double, val factory: () -> T) { +class Interval(value: Number, val factory: () -> T) { + + companion object { + inline operator fun invoke(value: Number) = Interval(value) { + K::class.java.newInstance() + } + } + + val value = value.toDouble() + + val longValue = Math.round(this.value) val inDays: Interval get() = converted() @@ -36,19 +46,12 @@ class Interval(val value: Double, val factory: () -> T) { val inNanoseconds: Interval get() = converted() - val longValue = Math.round(value) inline fun converted(): Interval { val otherInstance = OtherUnit::class.java.newInstance() return Interval(value * factory().conversionRate(otherInstance)) } - companion object { - inline operator fun invoke(value: Double) = Interval(value) { - K::class.java.newInstance() - } - } - operator fun plus(other: Interval): Interval { val newValue = value + other.value * other.factory().conversionRate(factory()) return Interval(newValue) { factory() } @@ -116,25 +119,25 @@ class Nanosecond : TimeUnit { val Number.days: Interval - get() = Interval(this.toDouble()) + get() = Interval(this) val Number.hours: Interval - get() = Interval(this.toDouble()) + get() = Interval(this) val Number.minutes: Interval - get() = Interval(this.toDouble()) + get() = Interval(this) val Number.seconds: Interval - get() = Interval(this.toDouble()) + get() = Interval(this) val Number.milliseconds: Interval - get() = Interval(this.toDouble()) + get() = Interval(this) val Number.microseconds: Interval - get() = Interval(this.toDouble()) + get() = Interval(this) val Number.nanoseconds: Interval - get() = Interval(this.toDouble()) + get() = Interval(this)