How can I have a type that represents a Double tha...
# announcements
v
How can I have a type that represents a Double that is within a given range? For example I’d like to have a type that holds a double that is guaranteed to be between 0 and 1. I had a look at
inline class
but it does not provide
init
so I have nowhere to place an
assert
. Any ideas?
d
You can provide a static constructor.
Make the actual constructor
internal
.
v
How can the static constructor access the argument?
d
My bad. By static constructor I meant a top-level function.
v
How would that look? Let’s say we start with this normal class, which I would like to be
inline class
(for performance and so that my type Score can be used directly without doing Score.score)
Copy code
class Score(val score: Double) {
    init {
        if (score < 0 || score > 1) throw IllegalArgumentException("Score must be in range [0, 1].")
    }
}
d
Copy code
inline class Score internal constructor(val score: Double)

fun createScore(score: Doublue): Score {
    if (score < 0 || score > 1) throw IllegalArgumentException("Score must be in range [0, 1].")
    return Score(score)
}
v
Oh, I see! However, this still allows a
Score
to be initialized incorrectly by not using the
createScore
wrapper
s
Not outside the same module though
v
Fair point, however, I now see that
Primary constructor of inline class must be public
.
d
You can use the
@PublishedApi
attribute, or whatever it's called.
k
I don't think that's right @Dominaezzz, that for when you use a private property from within a public inline function.
Also AFAIK there's no way to constrain the allowed values in an inline class (yet?).
(because Java code would always be able to pass illegal values)
d
I've seen stuff like this used in stdlib.... but then it's stdlib 🤷🏼 .
Check out the
Result
inline class for instance.
Can Java create inline classes? Could've sworn it's hidden from java.
k
That's what I said right, they use
@PublishedApi
to use an
internal
property in
public inline
functions.
But yeah,
Result
is weird in a couple of ways.