Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Variables in Kotlin

Variables in Kotlin

📌 Variables in Kotlin

In Kotlin, variables are used to store data. Kotlin provides two types of variables:

  1. Immutable (Read-only) → val

  2. Mutable (Changeable) → var


✅ 1. Immutable Variables (val)

  • Declared using the val keyword.

  • Value cannot be changed after assignment.

  • Similar to final in Java.

📌 Example:

kotlin

name = "Vikash"val age = 30println("Name: $name, Age: ")

  • name and age cannot be reassigned.


✅ 2. Mutable Variables (var)

  • Declared using the var keyword.

  • Value can be changed or reassigned.

📌 Example:

kotlin

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 TypeDescriptionExample
IntInteger valuesvar num: Int = 100
DoubleDecimal numbersvar pi: Double = 3.14
FloatSmaller floating-point numbersvar rate: Float = 10.5f
BooleanTrue/False valuesvar isActive: Boolean = true
CharSingle charactervar letter: Char = 'A'
StringText datavar 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:

kotlin

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:

kotlin

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 val is a compile-time constant and should be initialized with a value directly.

📌 Example:

kotlin

constval PI = 3.14159println("Value of PI: $PI")


✅ Conclusion

  • Use val for immutable variables (read-only).

  • Use var for mutable variables (modifiable).

  • Use lateinit for deferred initialization.

  • Use ? for nullable variables.

  • Use const val for constants.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql