Google News
logo
Kotlin - Interview Questions
What are nullable types in Kotlin?
Nullable types in Kotlin allow variables to hold either a non-null value or a null value. By default, Kotlin enforces null safety, aiming to eliminate null pointer exceptions at compile-time. Nullable types are denoted by appending a question mark (`?`) to the type declaration.

In Kotlin, variables declared without the nullable modifier (`?`) are considered non-nullable, meaning they cannot hold a null value. This is different from Java, where any reference type can hold a null value by default. By making nullability explicit in Kotlin's type system, the compiler can enforce null safety and provide compile-time checks to prevent null-related errors.

Here's an example that demonstrates nullable types in Kotlin :
var name: String? = "John" // 'name' is nullable, it can hold a String or null
var age: Int = 25 // 'age' is non-nullable, it can only hold an Int

name = null // Assigning null to a nullable variable is allowed
age = null // Compilation error: Null cannot be a value of a non-null type Int​
In the above code snippet, the `name` variable is declared as nullable by appending `?` to the type declaration (`String?`). It can hold a String value or a null value. On the other hand, the `age` variable is declared as non-nullable (`Int`), and assigning null to it would result in a compilation error.

When working with nullable types, Kotlin provides several null-safe operators and functions to handle potential null values, such as the safe call operator (`?.`), the Elvis operator (`?:`), and the safe cast operator (`as?`). These constructs allow developers to safely access properties, call methods, or provide default values in scenarios where the value might be null.

By explicitly marking nullable types, Kotlin encourages developers to handle nullability explicitly, reducing the occurrence of null pointer exceptions and improving the overall reliability and safety of the code.

It's worth noting that Kotlin also offers platform types (`T!`), which are used when interoperating with Java code that has unknown nullability information. Platform types are treated as nullable in Kotlin and require careful handling to ensure null safety.
Advertisement