Converting a while loop with assignment from Java to Kotlin

With so many apps to develop in so little time, I believe in the DRY method- Don’t Repeat Yourself. Whenever I come across a functionality that was already incorporated in one of my many previous apps, I usually go to my private reusable code repository (which I also keep up-to-date with the code I feel sure to become a reusable piece) and simply copy & paste the code from there.

With the announcement of Kotlin support by Google for Android Development and the whole ‘Android Kotlin vs Java’ charade that followed, there is a drastic migration of Android developers from Java to Kotlin.

Coming back to copy & paste. While copying Java code and pasting it to our new classes in Kotlin, Android Studio pretty much does all the necessary conversions from Java to Kotlin. There are only a few instances where we need to re-write the Java code in Kotlin.

Being a new member of the club- Learn Kotlin, I came across one such instance where “manually” converting a while loop with an assignment inside the condition from Java to Kotlin took my precious 30 minutes and a few hairs off of my head.

Java code we are so used to copy & paste:

The devil that drove me nuts was: while ((count = input.read(data)) != -1)

After many attempts and many searches, I was finally able to convert this particular Java code to Kotlin like so:

Let function let us use a property- do something with it and return a value.

In the above example, ‘let’ takes in the result from `input. read(data)`(the length of the input bytes read)- represented by ‘it’, assigns this value to `count`, and uses `it!=-1` Boolean result as the while loop condition.

Notice the ‘;’ in between the 2 statements inside let? In Kotlin programming language, If you want to write both statements: `count = it` and `it != -1` in a single line within a block {}, you need to separate both statements using a ‘;’ else you can always write the statements in 2 separate lines. It merely depends on your coding style.

Quite easy, right?

Categories