Variables in Kotlin Programming language

0

Variables in Kotlin

Variables in Kotlin Programming language


Variables in Kotlin allow you to store and reuse data throughout your program. You can think of them as containers for holding information, such as numbers, text, or even results from calculations.

There are two main types of variables in Kotlin:

  • var – Mutable (can change).
  • val – Immutable (cannot change).

1. Mutable Variables (var)

A variable declared with var can be changed after it's initially assigned. This is useful when the value is expected to update during the program.

Example:


fun main() {
    var score = 50
    println("Initial score: \$score")  // Output: Initial score: 50

    score = 80  // Changing the value
    println("Updated score: \$score")  // Output: Updated score: 80
}

Explanation:

  • We declare a variable score using var and assign it the value 50.
  • Later, we change the value of score to 80. This is possible because var allows the value to be modified.

2. Immutable Variables (val)

A variable declared with val cannot be changed once it’s assigned. This is useful when you don’t want the value to be modified accidentally.

Example:


fun main() {
    val pi = 3.14
    println("Value of pi: \$pi")  // Output: Value of pi: 3.14

    // pi = 3.14159  // Error! Can't change the value of 'pi'
}

Explanation:

  • We declare a variable pi using val and assign it the value 3.14.
  • If we try to change the value of pi, Kotlin will give an error because val makes the variable immutable.

When to Use var and val

  • Use var when you expect the value to change during the program. Example: a score that updates in a game.
  • Use val when you know the value will not change. Example: a constant value like pi or a configuration setting.

Benefits of Using val:

  • Prevents accidental changes to important values.
  • Helps make your code more predictable and easier to debug.

Post a Comment

0Comments

Post a Comment (0)