hfhbd
06/28/2021, 1:07 PMDouble
usage in my project with physical classes, like kiloWatt per Hour.
before:
data class Holder(val output: Double)
now:
data class Holder(val output: Kwh)
value class Kwh(val value: Double)
Now I want to use the default math operators, plus, minus unaryPlus, unaryMinus. Is there any possibility to create default operator functions without copy paste?Big Chungus
06/28/2021, 1:09 PMSourabh Rawat
06/28/2021, 1:12 PMhfhbd
06/28/2021, 1:29 PMvalue class Kwh(val double: Double): Number by double
does not work for value classes.
@Big Chungus Yeah, I use this workaround currently too, but I hoped, there would be a better wayBig Chungus
06/28/2021, 1:30 PMhfhbd
06/28/2021, 2:28 PMvalue class
, see also https://youtrack.jetbrains.com/issue/KT-46202
FYI:
@JvmInline
@JsExport
@Serializable
public value class Kwh(public override val value: Int) : Unit<Int, Kwh> {
public override fun from(value: Int): Kwh = value.kwh
}
public val Int.kwh: Kwh get() = Kwh(this)
public interface Unit<MathT, T> {
public val value: MathT
public fun from(value: MathT): T
}
@JvmName("plusInt")
public operator fun<T: Unit<Int, T>> Unit<Int, T>.plus(other: T): T = from(value + other.value)
@JvmName("minusInt")
public operator fun<T: Unit<Int, T>> Unit<Int, T>.minus(other: T): T = from(value - other.value)
@JvmName("unaryMinusInt")
public operator fun<T: Unit<Int, T>> Unit<Int, T>.unaryMinus(): T = from(-value)
public operator fun<T: Unit<Double, T>> Unit<Double, T>.plus(other: T): T = from(value + other.value)
public operator fun<T: Unit<Double, T>> Unit<Double, T>.minus(other: T): T = from(value - other.value)
public operator fun<T: Unit<Double, T>> Unit<Double, T>.unaryMinus(): T = from(-value)