What's wrong with this Kotlin code?
val emojis = listOf(“❤️️“, “🍔”)
val emojiIndex = someNullableInt ?: 0 % (emojis.size - 1)
val selectedEmoji = emojis[emojiIndex]
Let's decompile it to java code:
List emojis = CollectionsKt.listOf(new String[]{“❤️️“, “🍔”})
int emojiIndex = someNullableInt != null ? someNullableInt : 0 % (this.emojis.size() - 1);
String selectedEmoji = (String)this.emojis.get(emojiIndex);
Can you see the problem now?
the answer is below, don't look straight away :)
Answer:
In case someNullableInt is not null, emojiIndex will be assigned with the original value of someNullableInt and not its modulo.
This can cause indexOutOfBoundException.
how can we fix it?
the answer is below, don't look straight away :)
To fix it we need to add () around someNullableInt ?: 0 ->
val emojiIndex = (someNullableInt ?: 0) % (emojis.size - 1)
Which will compile to the following java code:
List emojis = CollectionsKt.listOf(new String[]{“❤️️“, “🍔”})
int emojiIndex = (someNullableInt != null ? someNullableInt : 0) % (this.emojis.size() - 1);
String selectedEmoji = (String)this.emojis.get(emojiIndex);
as you can see, now it will do modulo as expected. Case solved.
Thank you for reading, look for our next Byte
Made with ❤️ by Sanga
Top comments (0)