kotlin中的while或if怎么先取值,后比较

例如java中这么写的

int dataSize;
while ((dataSize = input.read()) != -1) {

}

在kotlin中这么写是报错的

assignments are not expressions,and only expressions are allowed in this connect
阅读 9.1k
5 个回答

kotlin不支持在条件里面包含赋值语句,你可以使用do...while()

用apply, also这种,
while (input.read().apply{ d = this } != -1)

while ((input.read().also { dataSize = it }) != -1) {

}

或者

while ((input.read().apply { dataSize = this }) != -1) {

}