In Kotlin, variables can be declared using either the val
keyword for immutable (read-only) variables or the var
keyword for mutable (modifiable) variables. Understanding how to declare variables and their scope is essential in Kotlin programming.
Note:
Variables in Kotlin are statically typed, meaning the type of the variable is known at compile time. However, Kotlin also supports type inference, allowing you to skip explicitly specifying the type if it can be inferred from the initializer.
To declare an immutable variable, use the val
keyword. Once initialized, the value of a val
variable cannot be changed.
val name: String = "Kotlin" println(name) // Output: Kotlin
To declare a mutable variable, use the var
keyword. You can modify the value of a var
variable after it has been initialized.
var age: Int = 25 println(age) // Output: 25 age = 30 println(age) // Output: 30
Kotlin can infer the type of a variable based on its initializer. If you do not specify the type, Kotlin will automatically choose the type for you.
val language = "Kotlin" // Type inferred as String var year = 2025 // Type inferred as Int
You can declare constants in Kotlin using the const
keyword. Constants must be of a primitive type or String and must be initialized at compile time.
const val MAX_USERS: Int = 100 println(MAX_USERS) // Output: 100
The scope of a variable defines where it can be accessed. Variables declared inside a function are local to that function, while variables declared outside functions are accessible throughout the program.
fun example() { val localVar = "I'm local" println(localVar) // Accessible here } // println(localVar) // Error: Cannot access localVar outside the function
In Kotlin, understanding variables, their mutability, and scope is essential for writing flexible and efficient code. You should use val
when you don't intend to modify the variable's value and var
when you need to update it. Kotlin's type inference simplifies the declaration process, making your code more concise and readable.
Quick Tip:
Always use val
for variables that do not change. This makes your code easier to understand and maintain.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!