DEV Community

Cover image for Kotlin Emojis Riddle 😈
liskov for Sanga

Posted on

3 2

Kotlin Emojis Riddle 😈

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs