

Don’t use withDefault, use getOrDefault when you need to rely on a fallback value.

This program will actually output default as we intended (because the key "2" is missing). What do you expect the outcome of this program to be? fun main (args: Array). Let’s start off with a rather simple “hello world” example. In this post I’ll show you 7 code snippets containing common mistakes (I made) when programming in Kotlin. Or maybe even worse: I can’t explain why the code DOES work. And even now I have some experience, every once in a while, when conducting a Kotlin training or when on a Kotlin assignment, I encounter situations where I simply cannot explain why the code doesn’t work the way I intended. Have you ever felt like this kid when programming? I sure did! When I got into Kotlin development I felt like this kid many many times. Option 2 would therefore usually be my choice, but I would use a sealed class that actually represents my domain data instead of the generic "string or int".This article was originally published at my personal blog on March 9, 2023. Usually the need for union types stems from using plain generic primitive types to represent meaningful domain data that could maybe better be expressed using more specific custom domain types. I am wondering about the actual use case at hand, though. If you extend TreeMap you will save some overhead as opposed to composition, but it shouldn't matter much.

This has the advantage of encapsulating the logic and exposing a neat API for the consumers. Use a custom map type, with independent accessors for ints and strings, but backed by a single TreeMap behind the scenes. That being said, maybe your domain can be better modeled with clearer names than Int or String, so it might actually improve the consumer's experience to define such types. Also, this puts the burden of (un)wrapping on the consumer side. This will have some runtime overhead for wrapping/unwrapping the int/string objects for each insertion/access. Use a custom sealed class to encapsulate your " Int or String" type, and use it in a regular TreeMap. Use TreeMap, which is the simplest of all, but it allows more types than just Int and String, and requires additional conversion boilerplate on the consumer side when accessing values. There is no union type in Kotlin, so you can't directly express this.
