DEV Community

loading...
Cover image for Kotlin Emojis Riddle 😈
Sanga

Kotlin Emojis Riddle 😈

liskov profile image liskov ・1 min read

What's wrong with this Kotlin code?

val emojis = listOf(“❤️️“, “🍔”)
val emojiIndex = someNullableInt ?: 0 % (emojis.size - 1)
val selectedEmoji = emojis[emojiIndex]
Enter fullscreen mode Exit fullscreen mode

Alt Text

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);
Enter fullscreen mode Exit fullscreen mode

Can you see the problem now?

the answer is below, don't look straight away :)

Alt Text

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

Alt Text

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);
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)

pic
Editor guide