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.
Practice
? after its type?Solution
Step 1: Understand Kotlin's default type behavior
Kotlin types are non-nullable by default, meaning variables cannot holdnullunless specified.Step 2: Check the effect of missing
Without??, the variable type is non-nullable, so it cannot holdnull.Final Answer:
The variable cannot holdnullvalues. -> Option AQuick Check:
Non-nullable type = nonullallowed [OK]
? means no null allowed [OK]- Thinking variables are nullable by default
- Assuming variables initialize to null automatically
- Confusing
lateinitwith nullability
null values?Solution
Step 1: Identify nullable type syntax
Adding?after the type allows the variable to holdnull.Step 2: Check initialization
Nullable variables must be initialized or declared withnullexplicitly, soval name: String? = nullis correct.Final Answer:
val name: String? = null -> Option AQuick Check:
Nullable type with?and initialized tonull[OK]
? and initialize nullable variables [OK]- Declaring nullable without
? - Not initializing nullable variables
- Assigning
nullto non-nullable types
fun main() {
val text: String? = null
println(text?.length ?: "No text")
}Solution
Step 1: Understand safe call operator usage
Thetext?.lengthsafely accesseslengthonly iftextis notnull.Step 2: Evaluate the Elvis operator
Sincetextisnull,text?.lengthisnull, so the Elvis operator?:returns "No text".Final Answer:
No text -> Option DQuick Check:
Safe call + Elvis operator returns fallback [OK]
- Expecting 0 instead of fallback string
- Confusing safe call with normal call
- Thinking code causes error due to null
fun main() {
val number: Int = null
println(number)
}Solution
Step 1: Check variable type and assignment
The variable 'number' is declared as non-nullable Int but assignednull, which is not allowed.Step 2: Understand Kotlin null safety rules
Non-nullable types cannot holdnull, so this causes a compilation error.Final Answer:
Cannot assign null to a non-nullable type Int. -> Option BQuick Check:
Non-nullable types rejectnullassignments [OK]
- Thinking semicolon is required
- Assuming var fixes null assignment
- Ignoring Kotlin's null safety
val input: String?. You want to print its length only if it is not null, otherwise print "Empty input". Which Kotlin code correctly does this?Solution
Step 1: Understand nullable variable usage
Sinceinputcan benull, we must check before accessinglength.Step 2: Evaluate each option
println(input.length ?: "Empty input") is invalid becauselengthis Int, not nullable, so Elvis operator on it is wrong.
println(if (input != null) input.length else "Empty input") safely checksnulland prints length or fallback.
println(input!!.length) uses!!which throws exception ifnull.
println(input?.length) printsnullifinputisnull, not the string "Empty input".Final Answer:
println(if (input != null) input.length else "Empty input") -> Option CQuick Check:
Explicit null check with if-else for safe access [OK]
- Using !! and risking exceptions
- Misusing Elvis operator on non-nullable Int
- Printing null instead of fallback string
Ready to prove it?
Pass the test and this pattern moves unknown
