Skip to content

Instantly share code, notes, and snippets.

@yankeppey
Created August 31, 2022 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yankeppey/1c61eaaff0b4f434ba02250d901a4b60 to your computer and use it in GitHub Desktop.
Save yankeppey/1c61eaaff0b4f434ba02250d901a4b60 to your computer and use it in GitHub Desktop.
Unitless Velocity (like kotlin.time.Duration)
/**
* 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