Error in control flow "while" with kotlin

Viewed 375

I have the following code in 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));

            }

I am updating my app to Kotlin, but in the WHILE, I have an error.

In this piece of code, I get the following error:

Assignments are not expressions, and only expressions are allowed in this context

            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));

            }

Any suggestions to eliminate the error.

2 Answers

In Kotlin assignments, such as count = input.read(data)) != -, cannot be used as expressions, i.e. count = xy does not return a boolean and thus cannot be evaluated by while.

You can change the code like this:

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

Also note that Kotlin provides sophisticated means for copying streams:

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