I have a condition like this:
if (value in 0..10 || value in 20..30 || value in 40..50) {
//do something
}
I wanted to put these range of values in a constant or something else that looks cleaner, I tried
const val values = {
0..10
20..30
40..50
}
but I get the error Const 'val' has type '() -> IntRange'. Only primitives and String are allowed
Is there a way to do this or do you have any other suggestion?
I have a condition like this:
if (value in 0..10 || value in 20..30 || value in 40..50) {
//do something
}
I wanted to put these range of values in a constant or something else that looks cleaner, I tried
const val values = {
0..10
20..30
40..50
}
but I get the error Const 'val' has type '() -> IntRange'. Only primitives and String are allowed
Is there a way to do this or do you have any other suggestion?
Share Improve this question asked Nov 19, 2024 at 14:53 AethiaAethia 491 silver badge9 bronze badges 2 |1 Answer
Reset to default 1You can use something like this.
fun main() {
val list = listOf(0..10, 20..30, 40..50);
val value = 22;
if (list.any { value in it }) {
println("Hello, world!!!")
}
}
I can only think of this way to combine the logic. But your way is already simple enough.
Array<IntRange>
would be[0..10, 20..30, 40..50]
; note the square brackets and commas. But even then it can't be aconst
. – Thomas Commented Nov 19, 2024 at 15:05value % 20 <= 10
. – broot Commented Nov 19, 2024 at 18:26