Nullable Types
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 13 of 93.
Sometimes you genuinely need a variable that can hold "nothing." For example, a user's middle name might not exist, or a search might return no results. Kotlin allows this through nullable types.
To make a type nullable, add a ? after the type name:
fun main() {
var middleName: String? = "Marie"
middleName = null // This is now allowed!
val age: Int? = null // Can hold an Int or null
}The ? tells Kotlin: "This variable might be null, so be careful with it." Without the ?, the type is non-nullable and can never hold null.
Important: Nullable and non-nullable types are different. You cannot directly assign a nullable value to a non-nullable variable:
fun main() {
val nullableName: String? = "Alice"
val regularName: String = nullableName // Error!
}This distinction is intentional. It forces you to handle the possibility of null before using the value. In the upcoming lessons, you'll learn the safe ways Kotlin provides to work with nullable values.
Challenge
EasyDeclare the following nullable variables:
- A nullable
Stringnamednicknamewith the value"Shadow" - A nullable
Intnamedagewith the valuenull - A nullable
Doublenamedbalancewith the value99.5
Then print all three values on separate lines using println().
Remember to use the
?after the type name to make it nullable. Printing anullvalue will display the wordnull.
Try it yourself
fun main() {
// TODO: Declare the following nullable variables:
// 1. A nullable String named 'nickname' with value "Shadow"
// 2. A nullable Int named 'age' with value null
// 3. A nullable Double named 'balance' with value 99.5
// Then print all three values on separate lines
}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