https://kotlinlang.org logo
#announcements
Title
# announcements
v

Viktor Qvarfordt

08/03/2019, 12:20 PM
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

Dominaezzz

08/03/2019, 12:25 PM
You can provide a static constructor.
Make the actual constructor
internal
.
v

Viktor Qvarfordt

08/03/2019, 12:45 PM
How can the static constructor access the argument?
d

Dominaezzz

08/03/2019, 12:46 PM
My bad. By static constructor I meant a top-level function.
v

Viktor Qvarfordt

08/03/2019, 12:47 PM
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

Dominaezzz

08/03/2019, 12:49 PM
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

Viktor Qvarfordt

08/03/2019, 12:50 PM
Oh, I see! However, this still allows a
Score
to be initialized incorrectly by not using the
createScore
wrapper
s

SiebelsTim

08/03/2019, 12:53 PM
Not outside the same module though
v

Viktor Qvarfordt

08/03/2019, 12:54 PM
Fair point, however, I now see that
Primary constructor of inline class must be public
.
d

Dominaezzz

08/03/2019, 12:55 PM
You can use the
@PublishedApi
attribute, or whatever it's called.
k

karelpeeters

08/03/2019, 4:34 PM
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

Dominaezzz

08/03/2019, 4:36 PM
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

karelpeeters

08/05/2019, 7:07 AM
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.
4 Views