Mobile Development Kotlin Subjective
Oct 04, 2025

Explain the difference between val and var in Kotlin.

Detailed Explanation
Kotlin uses two keywords for variable declaration:\n\n1. val (Value - Immutable)\n• Read-only reference, cannot be reassigned\n• Similar to final in Java\n• Example:\n\nval name = "John"\n// name = "Jane" // Compilation error\n\n\n2. var (Variable - Mutable)\n• Can be reassigned after initialization\n• Value can change during execution\n• Example:\n\nvar age = 25\nage = 26 // OK\n\n\n3. Important Notes\n• val makes the reference immutable, not the object\n• Example:\n\nval list = mutableListOf(1, 2, 3)\nlist.add(4) // OK - object is mutable\n// list = mutableListOf(5, 6) // Error - reference immutable\n\n\n4. Best Practice\n• Use val by default for immutability\n• Use var only when reassignment is needed\n• Improves code safety and readability
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback