What if your program could stop crashing from missing values before you even run it?
Why Non-nullable types by default in Kotlin? - Purpose & Use Cases
Imagine you are writing a program that handles user data. You have many variables that might sometimes have no value, so you leave them empty or null. But later, when you try to use these variables, your program crashes unexpectedly because it tried to use a value that wasn't there.
Manually checking every variable to see if it is null before using it is slow and tiring. It's easy to forget a check, which causes bugs and crashes. This makes your code messy and hard to read, and debugging becomes a nightmare.
Non-nullable types by default mean that variables cannot be null unless you explicitly say they can be. This forces you to think about null values upfront and handle them safely. The compiler helps catch mistakes early, so your program is safer and cleaner.
var name: String? = null
println(name?.length) // safe, prints null if name is nullvar name: String = "John"
println(name.length) // safe, cannot be nullThis concept lets you write safer programs that avoid unexpected crashes from missing values, making your code more reliable and easier to maintain.
Think of a contact app where every contact must have a phone number. By using non-nullable types, you ensure the phone number is always present, preventing errors when calling or messaging.
Variables are non-nullable by default, preventing accidental null use.
You must explicitly allow nulls, making your intentions clear.
The compiler helps catch null-related errors early, improving safety.