3 ms·
Kotlin provides pretty nice syntax sugar for that: num.coerceIn(min..max) That's it. This human reader finds it considerably more readable. It also has
by V-2 6y ago
Kotlin provides pretty nice syntax sugar for that:
num.coerceIn(min..max)
That's it. This human reader finds it considerably more readable.
It also has
coerceAtLeast
and
coerceAtMost
- nitrogen 6y agoDoes kotlinc optimize away inline ranges like that, or does this result in a range object being constructed and discarded?
- RandomBK 6y agoI haven't heard of any instances of Kotlin itself optimizing these things away, but the JVM may be able to do so during its various JIT passes. It's definitely not something you can necessarily rely on, though. Luckily, these convenience methods are usually implemented as inline extension functions, so the whole thing will get inlined into the calling method, making JIT optimization more likely.
- sanbor 6y agoThis is what I love about kotlin. The standard library has a good coverage of these kinds of problems and it is done in a simple an clean way. I had the same feeling with Python, the language got you cover with mundane tasks and you don't have to spend time researching libs that do it for you (or spend your time doing a clamp implementation + tests).