Assignment not allowed in while expression?

前端 未结 5 832
隐瞒了意图╮
隐瞒了意图╮ 2020-12-29 06:28

In Java we can usually perform an assignment within the while condition. However Kotlin complains about it. So the following code does not compile:



        
5条回答
  •  悲&欢浪女
    2020-12-29 07:20

    In cases you just want to replace while ((x = y.someFunction()) != null) you may use the following instead:

    generateSequence { y.someFunction() }
              .forEach { x -> /* what you did in your while */ }
    

    generateSequence will extract you all the values one by one until the first null is reached. You may replace the .forEach with a reduce or fold (or anything else that seems appropriate ;-)) if you want to keep the last value or sum up the values to something else.

    For your specific use case however you may just use what JB Nizet in his answer has shown or use useLines:

    reader.useLines {
      it.forEach(::println)
    }
    

    .forEachLine is probably the next best short-hand solution to that specific readLine-problem (already answered here) if you know you just want to read all lines and then stop.

提交回复
热议问题