【问题标题】:How to return after get value from foreach in kotlin [closed]从kotlin中的foreach获取值后如何返回[关闭]
【发布时间】:2020-08-11 21:50:09
【问题描述】:

我在这里点击返回非空值来调用我的 api。请告诉我如何调用一次api,谢谢。

        barcodes.forEach {
            if (!it.displayValue.isNullOrEmpty()) {
                barCode = it.displayValue!!
            }   
        }
        if (barCode.isNotEmpty()) {
            viewModel.callMyAPI(barCode)
            stop()
        }

【问题讨论】:

    标签: java android for-loop kotlin foreach


    【解决方案1】:

    您应该改用find 方法。它搜索满足谓词的元素,并在找到时停止查找。如果它没有找到任何元素,它将返回 null。

    类似这样的:

    val barCode = barcodes.find { !it.displayValue.isNullOrEmpty() }?.displayValue
    
    if (barCode != null) {
        viewModel.callMyAPI(barCode)
        stop()
    }
    

    【讨论】:

      【解决方案2】:
      1. 在foreach中继续:

        fun iterateForEach() {
                val listToTest = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
                listToTest.forEach {
                   if (it == 5) return@forEach
                     println(it)
        }
        }
        

      2:break in for each,在run loop中使用,它会执行

      run loop@{
          listOf(1, 2, 3, 4, 5).forEach {
              if (it == 3) return@loop // non-local return from the lambda passed to run
              println(it)
          }
      }
      

      我认为您的情况需要 2 个。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-24
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 2019-09-29
        • 1970-01-01
        • 1970-01-01
        • 2021-08-08
        相关资源
        最近更新 更多