What does the !! (double-bang) operator do in Kotlin and why is it needed?
Hi everyone! I just started learning Kotlin after Java and came across a strange `!!` operator. For example, I saw this code:\n\n```kotlin\nval name: String? = getUserName()\nval length = name!!.length\n```\n\nI understand that `?` means the variable can be null. But why is `!!` needed? It seems like if I'm sure the value is not null, I can just use `?.` or write `if (name != null)`. And if I'm wrong, I'll get a NullPointerException — that's bad!\n\nIn Java, I'm used to checking for null with `if`, but here there's some aggressive operator. Maybe it's a crutch for those too lazy to write checks? Or are there situations where `!!` is actually justified? Please explain what it does, how it works, and whether it should be used at all in real projects. Code examples are welcome.
No answers yet.
Log in to leave an answer
Blogs