最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

kotlin - Is it possible to create a constant with a range of values? - Stack Overflow

programmeradmin1浏览0评论

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
  • The corrent syntax for an Array<IntRange> would be [0..10, 20..30, 40..50]; note the square brackets and commas. But even then it can't be a const. – Thomas Commented Nov 19, 2024 at 15:05
  • 2 BTW, if in your real case ranges are always such regular, then please be aware this is pretty much the same as: value % 20 <= 10. – broot Commented Nov 19, 2024 at 18:26
Add a comment  | 

1 Answer 1

Reset to default 1

You 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.

发布评论

评论列表(0)

  1. 暂无评论