
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:
1byte data[] = new byte[4096];
2int count;
3while ((count = input.read(data)) != -1) {
4 ..............
5}
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:
1val data = ByteArray(4096)
2var count = 0
3
4while (input.read(data).let {
5 count = it; it != -1
6 }) {
7 ..........
8}
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?
Heading 1
Heading 2
Heading 3
Heading 4
Heading 5
Heading 6
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Block quote
Ordered list
- Item 1
- Item 2
- Item 3
Unordered list
- Item A
- Item B
- Item C
Bold text
Emphasis
Superscript
Subscript