kotlin
  1. kotlin-nullable-non-nullable-types

Kotlin Nullable and Non-Nullable Types

In Kotlin, variables can be explicitly marked as either nullable or non-nullable. The difference between the two is whether or not they can hold a null value. In this tutorial, we'll discuss nullable and non-nullable types in Kotlin.

Syntax

To declare a nullable type in Kotlin, use the "?" symbol after the type. For example:

var str: String? = "hello"

To declare a non-nullable type, don't use the "?" symbol. For example:

var name: String = "John"

Example

Let's say you have a nullable variable that holds a string value:

var str: String? = "hello"

You can assign a null value to this variable:

str = null

However, if you try to assign a null value to a non-nullable variable:

var name: String = "John"
name = null // compilation error

You'll get a compilation error.

Output

If you try to access a null value of a nullable type variable, you'll get a null pointer exception. For example:

var str: String? = null
println(str.length) // null pointer exception

Explanation

Nullable types in Kotlin allow you to explicitly define whether or not a variable can hold a null value. This helps to prevent null pointer exceptions and makes your code safer. Non-nullable types, on the other hand, cannot hold a null value. This ensures that you can always access the value of a non-nullable type variable without the risk of a null pointer exception.

To access the value of a nullable variable, you need to use the safe operator "?.". This operator returns null if the variable is null, and the value of the variable otherwise. For example:

var str: String? = null
println(str?.length) // null

Use

Nullable and non-nullable types in Kotlin are useful for improving the safety of your code and reducing the risk of null pointer exceptions. They also make the code more readable as they clearly express the intention of whether or not a variable can hold a null value.

Important Points

  • Nullable types in Kotlin are marked with the "?" symbol after the type.
  • Non-nullable types in Kotlin do not have the "?" symbol.
  • Accessing a null value of a nullable type variable will result in a null pointer exception.
  • Use the safe operator "?." to access the value of a nullable type variable.

Summary

In this tutorial, we discussed nullable and non-nullable types in Kotlin. We looked at the syntax, examples, output, explanation, use, and important points of nullable and non-nullable types. With this knowledge, you can now use nullable and non-nullable types in your Kotlin code to make it safer and more readable.

Published on: