I have a float I want to pass around that should a...
# random
f
I have a float I want to pass around that should always be in a given range (0.0f.1.0f) I don't want to write asserts for it at every level of my app, only at I/O, how would you represent this?
Is this a good idea
Copy code
@JvmInline
value class Volume(val value: Float){
    init {
        assert(value in 0.0..1.0) {
            "Invalid volume: $value"
        }
    }
}
🙌 1
r
Yes
✅ 1
f
When writing tests for below, I get
Cannot invoke "kotlin.ranges.ClosedFloatingPointRange.contains(java.lang.Comparable)" because "Volume.volumeRange" is null
Any idea why?
Copy code
@JvmInline
value class Volume(val value: Float) {
    init {
        assert(value in volumeRange) {
            "Invalid volume: $value"
        }
    }

    companion object {
        val default = Volume(DEFAULT_VOLUME)
        val volumeRange = 0.0..1.0
    }
}
d
This is an initialisation order problem. Swap the order of
default
and
volumeRange
in the Companion object.
➕ 3
a
or wrap
Volume(DEFAULT_VOLUME)
with
by lazy {}
p
I wish the order was checked by the compiler, it's confusing to get the error as late as in runtime
👍 1
I recall KT-46771 and KT-25796 but both are resolved - is there one for the JVM?