Assignment not allowed in while expression?

前端 未结 5 842
隐瞒了意图╮
隐瞒了意图╮ 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:13

    And here is a short Kotlin-style general solution by Roman Elizarov:

    while (true) {
        val line = reader.readLine() ?: break
        println(line);
    }
    

    Here break has Nothing type that also helps to promote type inference for the line as non-nullable string.

提交回复
热议问题