Kotlin:为什么我不能在循环防守中做任务? [英] Kotlin: Why can't I do an assignment in a loop guard?

查看:83
本文介绍了Kotlin:为什么我不能在循环防守中做任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这种语法无效? IntelliJ报告的错误是在这样的上下文中只允许表达式(第2行)。我想知道是否有一些语法用于解决这个问题,因为Java允许在循环功能中使用这种类型的赋值。

Why is this syntax not valid? The error IntelliJ reports is that only expressions are allowed in such context (line 2). I am wondering if there is some syntax to use to get around this, as Java allowed this type of assignment in loop feature.

var c: Int;
while ((c = reader.read()) != 1) {
}


推荐答案

语法无效,因为 c = reader.read()不是Kotlin中的表达式 - 这可以防止所有 == vs = 错误。

The syntax is not valid, because c = reader.read() is not an expression in Kotlin – this prevents all the == vs = bugs.

你必须重写为:

while (true) {
    val c = reader.read()
    if (c == 1) break
    ...
}

这篇关于Kotlin:为什么我不能在循环防守中做任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆