Created
August 31, 2022 10:51
-
-
Save yankeppey/1c61eaaff0b4f434ba02250d901a4b60 to your computer and use it in GitHub Desktop.
Unitless Velocity (like kotlin.time.Duration)
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
/** | |
* Represents the velocity. | |
* | |
* To construct a velocity use either the extension function toVelocity, or the extension properties mph, metersPerSecond, and so on, | |
* avaiable on [Int], [Long], [Float] and [Double] numeric types. | |
* | |
* To get the value of this duration expressed in a particular duration units use the properties [inMetersPerSecond] and so on. | |
* | |
* @author Andrei Buneyeu | |
*/ | |
@Suppress("MemberVisibilityCanBePrivate") | |
@JvmInline | |
value class Velocity internal constructor(private val rawValue: Double) : Comparable<Velocity> { | |
companion object { | |
fun Int.toVelocity(unit: VelocityUnit): Velocity { | |
return Velocity(this * unit.ratio) | |
} | |
fun Long.toVelocity(unit: VelocityUnit): Velocity { | |
return Velocity(this * unit.ratio) | |
} | |
fun Float.toVelocity(unit: VelocityUnit): Velocity { | |
return Velocity(this * unit.ratio) | |
} | |
fun Double.toVelocity(unit: VelocityUnit): Velocity { | |
return Velocity(this * unit.ratio) | |
} | |
inline val Int.mph: Velocity get() = toVelocity(VelocityUnit.MILE_PER_HOUR) | |
inline val Int.metersPerSecond: Velocity get() = toVelocity(VelocityUnit.METER_PER_SECOND) | |
inline val Double.metersPerSecond: Velocity get() = toVelocity(VelocityUnit.METER_PER_SECOND) | |
inline val Float.metersPerSecond: Velocity get() = toVelocity(VelocityUnit.METER_PER_SECOND) | |
} | |
fun toDouble(unit: VelocityUnit): Double { | |
return rawValue / unit.ratio | |
} | |
val inMetersPerSecond: Double | |
get() = toDouble(VelocityUnit.METER_PER_SECOND) | |
override fun compareTo(other: Velocity): Int { | |
return this.rawValue.compareTo(other.rawValue) | |
} | |
} | |
enum class VelocityUnit(val ratio: Double) { | |
MILE_PER_HOUR(.44704), | |
METER_PER_SECOND(1.0), | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment