0
0
Android Kotlinmobile~3 mins

Why Variables (val, var) and null safety in Android Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app never crashed because of missing or changed data? Kotlin's variables and null safety make that possible!

The Scenario

Imagine writing an app where you keep track of user info like names and ages. You write code to store these details, but sometimes you forget if a value can change or if it might be missing. This causes bugs and crashes.

The Problem

Without clear rules, your app might crash when it tries to use a missing value (null). Also, if you accidentally change a value that should stay the same, your app behaves unpredictably. Fixing these bugs takes a lot of time and makes your code messy.

The Solution

Kotlin's val and var keywords clearly show if a value can change or not. Plus, Kotlin's null safety forces you to handle missing values carefully, preventing crashes before they happen.

Before vs After
Before
String name = null;
name = "Alice";
name = null; // Oops, no warning

String age; // No info if it can change
After
val name: String? = null // Nullable, must check before use
var age: Int = 0 // Mutable, can change safely
What It Enables

This lets you write safer, clearer apps that don't crash unexpectedly and are easier to understand and maintain.

Real Life Example

In a messaging app, you can safely handle when a user hasn't set a profile picture yet (null) without the app crashing, and you know which info can be updated or stays fixed.

Key Takeaways

val means a value won't change, var means it can.

Null safety helps avoid crashes by forcing you to handle missing values.

Using these makes your app more reliable and your code easier to read.