!! Operator: When and Why to Avoid It
Understand the non-null assertion operator, its risks, and better alternatives.
What Is !!?
The non-null assertion operator !! converts a nullable type to non-null. If the value is null at runtime, it throws NullPointerException.
Basic !! Usage
x!! returns x if non-null, otherwise throws NPE.
fun main() {
val name: String? = "Kotlin"
val len: Int = name!!.length // 6
println(len)
}All lessons in this course
- Nullable Types and the ? Modifier
- Safe Call ?. and Elvis ?: in Real Code
- let, also, and run with Nullable Receivers
- !! Operator: When and Why to Avoid It