VARIABLES

Variables in Kotlin are used to store data that can be referenced and manipulated within a program. Kotlin provides a flexible and type-safe way to declare variables with different levels of mutability and types.

Types of Variables:

  1. Immutable Variables (val):
  2. Mutable Variables (var):

Variable Declaration Examples:

  1. Immutable Variable (val):
val name: String = "John"
val age: Int = 25
// name = "Doe" // Error: Val cannot be reassigned

  1. Mutable Variable (var):
var city: String = "New York"
var temperature: Int = 30
city = "Los Angeles" // This is allowed

Type Inference:

Kotlin has type inference, meaning the type can be automatically inferred by the compiler based on the assigned value, so specifying the type is optional if it's clear from the context.

val name = "John"  // Compiler infers String
var age = 25       // Compiler infers Int