Alb*_*rtB 3 android while-loop kotlin
我在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));
}
Run Code Online (Sandbox Code Playgroud)
我正在将我的应用更新为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));
}
Run Code Online (Sandbox Code Playgroud)
任何消除错误的建议。
在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)
}
Run Code Online (Sandbox Code Playgroud)
另请注意,Kotlin提供了用于复制流的复杂方法:
val s: InputStream = FileInputStream("file.txt")
s.copyTo(System.out)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
172 次 |
| 最近记录: |