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

查看:24
本文介绍了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天全站免登陆