0
0
Android Kotlinmobile~5 mins

Variables (val, var) and null safety in Android Kotlin

Choose your learning style9 modes available
Introduction

Variables store information your app uses. Kotlin helps keep your app safe by making sure variables are used correctly and not null by mistake.

When you want to store a value that does not change, like a user's name.
When you need to store a value that can change, like a score in a game.
When you want to avoid app crashes by safely handling variables that might be empty or missing.
When you want to clearly tell the app if a variable can be empty or must always have a value.
Syntax
Android Kotlin
val name: String = "Alice"
var score: Int = 0
var nickname: String? = null

val means the variable cannot change after it is set.

var means the variable can change its value.

Adding ? after the type means the variable can be null (empty).

Examples
This creates a variable city that cannot change and must always have a value.
Android Kotlin
val city: String = "Paris"
This creates a variable age that can change from 25 to 26.
Android Kotlin
var age: Int = 25
age = 26
This variable can start empty (null) and later get a value.
Android Kotlin
var middleName: String? = null
middleName = "Lee"
Sample App

This program shows how to use val and var variables. It also shows how a variable can be null and later get a value.

Android Kotlin
fun main() {
  val firstName: String = "John"
  var points: Int = 10
  var nickname: String? = null

  println("Name: $firstName")
  println("Points: $points")
  println("Nickname: $nickname")

  points = 15
  nickname = "Johnny"

  println("Updated Points: $points")
  println("Updated Nickname: $nickname")
}
OutputSuccess
Important Notes

Trying to change a val variable will cause an error.

Variables without ? cannot be null, so Kotlin helps prevent crashes.

Use ?. or ?: operators to safely work with nullable variables.

Summary

val is for values that do not change.

var is for values that can change.

Adding ? after a type means the variable can be null (empty).