Menu
Coddy logo textTech

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 icon

Challenge

Easy

Declare the following nullable variables:

  • A nullable String named nickname with the value "Shadow"
  • A nullable Int named age with the value null
  • A nullable Double named balance with the value 99.5

Then print all three values on separate lines using println().

Remember to use the ? after the type name to make it nullable. Printing a null value will display the word null.

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
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground