Assignment not allowed in while expression?

前端 未结 5 831
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  旧时难觅i
    2020-12-29 07:33

    No, the best way, IMO, would be

    val reader = BufferedReader(reader)
    reader.lineSequence().forEach {
        println(it)
    }
    

    And if you want to make sure the reader is properly closed (as you would with a try-with-resources statement in Java), you can use

    BufferedReader(reader).use { r ->
        r.lineSequence().forEach {
            println(it)
        }
    }
    

提交回复
热议问题