```fun IntRange.clamp(value: Int) = when { val...
# announcements
k
Copy code
fun IntRange.clamp(value: Int) = when {
    value <= start -> start
    value >= endInclusive -> endInclusive
    else -> value
}
m
There's the
coerceAtLeast
,
coerceAtMost
and
coerceIn
extensions on Int.
Copy code
5.coerceIn(3..8) == 5
1.coerceIn(3..8) == 3
9.coerceIn(3..8) == 8
👍 4
k
Exactly what I wanted, thanks!
I looked trough everything on
IntRange
, that would have been a better place to put in I think.
🚫 1
@Pavlo Liapota I think coercing is not so much a part of ints, it's more a function of ranges.
p
I see your point. But for me it is more clear when you call function on
Int
to get a new
Int
. It is like you call
filter
or
map
on
List
to get another
List
.
k
Fair point as well.
p
The intension here is to limit value of
Int
and
Range
is just nice structure to pass max and min value.
k
Ah
5.coerceIn(min, max)
exists as well. That makes sense then.
👍 1
h
I really wanna make a library that allows you to delegate number declarations to ranges that constrain their value, e.g
val foo: Int by RestrictedInt(-2..5)
, but I ran into issues when I first started writing it and shelved it when other work came up. but here is the start...
k
Hmm, any reason you need a
RestrictedInteger
type and not all of it can be handled in the delegate? And what issue ls did you have?
h
I don't fully understand the question but I ran into an issue in the top level
compareTo()
functions, I think?