Kotlin Variables

Kotlin Tutorial

Kotlin Variables – Complete Guide

In Kotlin Variables is used to store data that can be used and changed during program execution.

Kotlin variables are declared using val and var.


 1. Types of Variables in Kotlin

Kotlin has two main types of variables:

  • val – Read-only (Immutable)
  • var – Mutable (Changeable)

 2. val – Read-Only Variable

Once assigned, its value cannot be changed.

 Invalid:

  •  Safer
  •  Preferred in Kotlin
  •  Similar to final in Java

 3. var – Mutable Variable

Value can be changed.

  •  Use only when modification is required

 4. Variable Declaration with Data Type

You can explicitly specify the type.

  •  Good for readability
  •  Helpful in large projects

 5. Type Inference (Automatic Type Detection)

Kotlin automatically detects the type.

  •  Cleaner syntax
  •  Less boilerplate

 6. Late Initialization (lateinit)

Used when variable will be initialized later.

  • Only for var 
  • Cannot be used with primitive types

Example:


 


7. Nullable Variables

By default, variables cannot be null.

To allow null:

  • Prevents NullPointerException

 8. Constant Variables (const val)

Compile-time constants.

  •  Faster
  •  Must be top-level or inside object

 9. Multiple Variable Declaration

Or:


 10. Variable Scope

 Local Variable

Declared inside a function.

 Global Variable

Declared outside all functions.


 Common Mistakes

  • Using var instead of val

  • Forgetting ? for nullable variables

  • Using lateinit for primitives

  • Declaring unused variables


 Best Practices

  •  Prefer val over var
  •  Use meaningful variable names
  • Keep scope minimal
  • Avoid unnecessary mutability

 Interview Questions – Kotlin Variable

Q1. Difference between val and var?
val is immutable, var is mutable.

Q2. Can val reference mutable objects?
Yes.

Q3. What is lateinit?
Late initialization of non-null variables.

Q4. Can Kotlin variable be null by default?
No.


 Summary

  • val → read-only
  • var → changeable
  •  Type inference supported
  •  Null safety built-in
  •  Cleaner than Java

You may also like...