What Is Null Safety
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 12 of 93.
In many programming languages, one of the most common errors is trying to access something that doesn't exist: a null value. This happens when a variable holds "nothing" instead of actual data.
Imagine asking for a user's name, but they never provided one. If your code tries to use that empty name without checking first, your program crashes. This type of bug is so common it's been called the "billion-dollar mistake."
Kotlin's Solution: Null Safety
Kotlin was designed to eliminate these crashes. By default, variables in Kotlin cannot hold null values:
fun main() {
var name: String = "Alice"
name = null // Error! Won't compile
}The compiler catches this problem before your code even runs. This is what makes Kotlin "null safe": the language itself prevents you from accidentally using null where it shouldn't be.
In the upcoming lessons, you'll learn how Kotlin lets you work with values that might be null when you actually need them, while still keeping your code safe from crashes.
Challenge
EasyDeclare two non-nullable variables to demonstrate Kotlin's null safety:
- A
Stringvariable namedusernamewith the value"Kotlin" - An
Intvariable namedscorewith the value100
Then print both values on separate lines using println().
Remember: In Kotlin, regular (non-nullable) types cannot hold
nullvalues. The compiler ensures your variables always contain valid data.
Try it yourself
fun main() {
// TODO: Write your code below
// Declare a non-nullable String variable named 'username' with value "Kotlin"
// Declare a non-nullable Int variable named 'score' with value 100
// Print both values on separate lines using println()
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground