Kotlin Variables
Learn how to store and manage data in Kotlin
📦 What are Kotlin Variables?
Variables in Kotlin are containers that store data values. Use 'val' for unchangeable values and 'var' for values that can change during program execution.
// Immutable variable (cannot be changed)
val name = "John"
// Mutable variable (can be changed)
var age = 25
age = 26 // This is allowed
Output:
name: John
age: 26
Variable Types
val (Immutable)
Cannot be changed after assignment
val pi = 3.14159
var (Mutable)
Can be changed after assignment
var counter = 0
Type Declaration
Explicitly specify variable type
val score: Int = 100
Type Inference
Kotlin automatically detects type
val message = "Hello"
🔹 Variable Declaration Examples
Here are different ways to declare variables in Kotlin:
// Basic variable declarations
val studentName = "Alice" // String (immutable)
var studentAge = 20 // Int (mutable)
val isStudent = true // Boolean (immutable)
var gpa = 3.85 // Double (mutable)
// With explicit types
val courseName: String = "Kotlin Programming"
var enrollmentCount: Int = 150
// Changing mutable variables
var temperature = 25
temperature = 30 // OK - var can be changed
// val cannot be reassigned
// studentName = "Bob" // Error! val cannot be reassigned
Output:
studentName: Alice
studentAge: 20
isStudent: true
gpa: 3.85
temperature: 30
🔹 Variable Naming Rules
Follow these rules when naming variables in Kotlin:
- Start with letter or underscore: name, _count, userName
- Use camelCase: firstName, totalAmount, isReady
- No spaces or special characters: except underscore
- Case sensitive: Name and name are different
- Avoid keywords: fun, class, if, etc.
// Good variable names
val firstName = "John"
val totalPrice = 99.99
val isLoggedIn = false
val user_id = 12345
// Bad variable names (avoid these)
// val 2name = "John" // Cannot start with number
// val first-name = "John" // Cannot use hyphen
// val class = "Math" // 'class' is a keyword
🔹 When to Use val vs var
Choose the right variable type for your needs:
🔸 Use val when:
- Value won't change (constants, configuration)
- Mathematical constants (pi, e)
- User input that stays the same
- Function results that don't change
🔸 Use var when:
- Value needs to change (counters, accumulators)
- User interface states
- Loop variables
- Temporary calculations
// val examples (immutable)
val appName = "My Kotlin App"
val maxUsers = 1000
val pi = 3.14159
// var examples (mutable)
var currentUser = "guest"
var loginAttempts = 0
var isConnected = false
// Updating var variables
currentUser = "john_doe"
loginAttempts = loginAttempts + 1
isConnected = true