Variables in Kotlin
📌 Variables in Kotlin
In Kotlin, variables are used to store data. Kotlin provides two types of variables:
Immutable (Read-only) →
valMutable (Changeable) →
var
✅ 1. Immutable Variables (val)
Declared using the
valkeyword.Value cannot be changed after assignment.
Similar to
finalin Java.
📌 Example:
name = "Vikash"val age = 30println("Name: $name, Age: ")
name and age cannot be reassigned.
✅ 2. Mutable Variables (var)
Declared using the
varkeyword.Value can be changed or reassigned.
📌 Example:
var count = 10println("Initial Count: $count")count = println("Updated Count: $count")
✅ Variable Declaration with Data Types
In Kotlin, you can explicitly declare the data type using : Type.
| Data Type | Description | Example |
|---|---|---|
Int | Integer values | var num: Int = 100 |
Double | Decimal numbers | var pi: Double = 3.14 |
Float | Smaller floating-point numbers | var rate: Float = 10.5f |
Boolean | True/False values | var isActive: Boolean = true |
Char | Single character | var letter: Char = 'A' |
String | Text data | var greeting: String = "Hello" |
✅ Type Inference in Kotlin
Kotlin supports type inference, meaning it can automatically detect the data type based on the assigned value.
📌 Example:
language = "Kotlin"// Type inferred as Stringvar year = 2025// Type inferred as Int
✅ Nullable Variables
In Kotlin, variables are non-nullable by default. If you need a variable to hold a null value, you must use ?.
📌 Example:
var name: String? = nullprintln("Name: $name") lateinitvar greeting: Stringfun() { greeting = "Hello, Kotlin!" println(greeting)}
✅ Constant Variables in Kotlin
If you need constants (values that won't change), use const val.
const valis a compile-time constant and should be initialized with a value directly.
📌 Example:
constval PI = 3.14159println("Value of PI: $PI")
✅ Conclusion
Use
valfor immutable variables (read-only).Use
varfor mutable variables (modifiable).Use
lateinitfor deferred initialization.Use
?for nullable variables.Use
const valfor constants.