使用 kotlin 的控制流"while"错误



我在JAVA中有以下代码:

byte[] data = new byte[1024];
int count;
int total = 0;
while ((count = input.read( data )) != -1) {
output.write( data, 0, count );
total += count;
publishProgress((int) (total * 100 / sizeFichero));
}

我正在将我的应用程序更新到 Kotlin,但在 WHILE 中,我遇到了一个错误。

在这段代码中,我收到以下错误:

赋值不是表达式,只允许在 这个背景

val data = ByteArray(1024)
var count: Int?
var total = 0
while ((count = input.read(data)) != -1) {
output.write( data, 0, count!! )
total += count!!
publishProgress((int) (total * 100 / sizeFichero));
}

消除错误的任何建议。

在 Kotlin 赋值中,例如count = input.read(data)) != -,不能用作表达式,即count = xy不返回布尔值,因此无法通过while计算。

您可以像这样更改代码:

var count = input.read(data)
while (count != -1) {
output.write( data, 0, count!! )
//...
count = input.read(data)
}

另请注意,Kotlin 提供了复制流的复杂方法:

val s: InputStream = FileInputStream("file.txt")
s.copyTo(System.out)

这是解决您的问题的方法:

val data = ByteArray(1024)
var count: Int?
var total = 0
while ({count = input.read(data);count }() != -1) {
output.write( data, 0, count!! )
total += count!!
publishProgress((int) (total * 100 / sizeFichero));
}

有关更多详细信息,请阅读以下讨论:

https://discuss.kotlinlang.org/t/assignment-not-allow-in-while-expression/339/6

相关内容

最新更新