KOTLIN Tutorial



VARIABLES IN KOTLIN


Variables in Kotlin

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.

Declaring Immutable Variables

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

Declaring Mutable Variables

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

Type Inference in Kotlin

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

Constants in Kotlin

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

Variables and Their Scope

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

Conclusion

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.


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review