Created
March 6, 2022 19:42
-
-
Save jcraane/503dd4f6ef3a592ea75c6e79646b45ae to your computer and use it in GitHub Desktop.
Simple implementation of Distance in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@JvmInline | |
value class Distance internal constructor(private val rawValue: Long) : Comparable<Distance> { | |
override fun compareTo(other: Distance) = this.rawValue.compareTo(other.rawValue) | |
val inWholeMeters: Long | |
get() = toLong(DistanceUnit.METERS) | |
val inWholeKilometers: Long | |
get() = toLong(DistanceUnit.KILOMETERS) | |
operator fun plus(other: Distance) = Distance(rawValue + other.rawValue) | |
operator fun minus(other: Distance) = Distance(rawValue - other.rawValue) | |
private fun toLong(targetUnit: DistanceUnit) = convertDurationUnit(rawValue.toDouble(), DistanceUnit.MILLIMETERS, targetUnit) | |
companion object { | |
val ZERO: Distance = Distance(0L) | |
inline val Long.meters get() = toDistance(DistanceUnit.METERS) | |
inline val Long.kilometers get() = toDistance(DistanceUnit.KILOMETERS) | |
inline val Int.meters get() = toDistance(DistanceUnit.METERS) | |
inline val Int.kilometers get() = toDistance(DistanceUnit.KILOMETERS) | |
inline val Double.kilometers get() = toDistance(DistanceUnit.KILOMETERS) | |
} | |
} | |
fun Long.toDistance(unit: DistanceUnit): Distance { | |
val inMillimeters = convertDurationUnit(this.toDouble(), unit, DistanceUnit.MILLIMETERS) | |
return Distance(inMillimeters) | |
} | |
fun Double.toDistance(unit: DistanceUnit): Distance { | |
val inMillimeters = convertDurationUnit(this, unit, DistanceUnit.MILLIMETERS) | |
return Distance(inMillimeters) | |
} | |
fun Int.toDistance(unit: DistanceUnit): Distance { | |
val inMillimeters = convertDurationUnit(this.toDouble(), unit, DistanceUnit.MILLIMETERS) | |
return Distance(inMillimeters) | |
} | |
private fun convertDurationUnit(value: Double, unit: DistanceUnit, target: DistanceUnit) = | |
unit.convert(value, target) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment