DhiWise Logo

Design Converter

  • Technologies
  • Resource
  • Pricing

Education

Kotlin val vs. var: Choosing the Right Option for Your Code

Last updated on Dec 11, 2024

5 mins read

If you're new to Kotlin or just brushing up on your skills, understanding these two keywords is a must! They play a big role in how you handle variables in your code.

In this blog, we’ll break down Kotlin val vs var, explain how they work, and help you choose the right one for every situation.

Let’s make coding in Kotlin simpler and more fun! 🚀

What Are val and var?

In Kotlin, the val keyword declares read-only variables, meaning the value assigned cannot be changed once initialized. Think of val as a final variable in Java. On the other hand, the var keyword declares mutable variables, meaning their values can be modified after declaration.

Syntax Overview

Here’s how you declare variables in Kotlin:

1val x: Int = 10 // Read-only variable 2var y: String = "Hello" // Mutable variable

Both val and var can be used as local variables, class properties, or even within functions. The key difference lies in mutability: val means immutable, while var allows reassignment.

Using val: Immutable Variables in Kotlin

When you use val, you are creating a variable whose value cannot be changed after it is initialized. This makes it functionally equivalent to a final variable in Java.

Key Points About val

  1. Immutable: The value assigned to a val property cannot be reassigned.

  2. Reference vs. Object Stored: While the reference of a val variable cannot change, the contents of the object stored may still be mutable.

  3. Used for Constants: If the value won’t change during the program’s lifecycle, declare it with val.

Example: Using val for Read-Only Variables

1val name: String = "Kotlin" 2// name = "Java" // Compiler error: Val cannot be reassigned 3 4println(name) // Output: Kotlin

Using var: Mutable Variables in Kotlin

The var keyword is used when you need a variable whose value can be updated. Unlike val, the compiler imposes no restrictions on reassignment for var.

Key Points About var

  1. Mutable: You can reassign a new value to a var variable.

  2. Best for Local Variables: Use var in situations where you expect the variable to change during runtime.

Example: Reassigning a Variable Declared with var

1var counter: Int = 0 2counter += 1 // Allowed 3println(counter) // Output: 1

Difference Between val and var

The fundamental difference is mutability:

val means the variable is immutable and its value cannot be reassigned.

var allows reassigning new values to the variable.

Key Comparisons

Aspectvalvar
MutabilityImmutable (cannot be changed)Mutable (can be reassigned)
ReassignmentNot allowedAllowed
Object StoredOnly the reference is immutableBoth reference and value can change
Similar to in Javafinal variableGeneral variable
Common Use CasesConstants, read-only propertiesChanging values like counters or states
Thread SafetySafer due to immutabilityRequires caution in multithreaded code
Syntax Exampleval x = 5var y = 10

Practical Use Cases: When to Choose val or var

val Use Cases

Immutable variables: Use val when the variable’s value will not change.

Compile-Time Constants: Ideal for storing values like configuration keys.

Default for Safety: Prefer val unless you explicitly need mutability.

Example: Immutable Class Properties

1class Person(val name: String, val age: Int) 2 3val john = Person("John", 30) 4// john.age = 31 // Compiler error

var Use Cases

Changing Values: Use var for counters, accumulators, or other variables that are expected to change.

Local Variables in Functions: Common in loops and conditions.

Example: Variable Reassignment in Loops

1fun main() { 2 var sum = 0 3 for (i in 1..5) { 4 sum += i 5 } 6 println(sum) // Output: 15 7}

The Nuances of val and var

Reference vs. Object

Even though val ensures that the reference cannot be changed, the object stored in the reference might still be mutable.

Example: Mutable Object Stored in val

1val numbers = mutableListOf(1, 2, 3) 2numbers.add(4) // Allowed, as the object stored is mutable 3println(numbers) // Output: [1, 2, 3, 4]

In contrast, a var reference can point to a completely new object:

1var list = mutableListOf(1, 2) 2list = mutableListOf(3, 4) // Allowed 3println(list) // Output: [3, 4]

Common Mistakes and Best Practices

Avoid Overusing var

Overusing var can make your Kotlin code harder to understand. Instead, use val wherever possible to ensure immutability.

Use val for Read-Only Variables

If you’re creating a constant or a property that cannot be changed, always prefer val.

Understand Default Behaviors

Kotlin encourages the use of immutable variables for better thread safety and predictability. Following this principle makes your code easier to debug.

Wrapping Up: Kotlin val vs. var Made Simple

Which one should you choose: Kotlin val or var? 🤔 It all depends on your use case!

In Kotlin, val is perfect when you want a value to stay constant, ensuring immutability and safer code. On the other hand, var is the go-to choice when you need flexibility to reassign values. Both have their unique roles, and knowing when to use them makes your Kotlin journey smoother. 🚀

So, as you write your next line of Kotlin code, think about what your variable needs to do. Is it a steadfast companion or a dynamic changemaker? The answer will guide your choice between val and var.

Happy coding! 💻🎉

Short on time? Speed things up with DhiWise!

Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!

You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.

Sign up to DhiWise for free

Frequently asked questions

What is the difference between var and val in Kotlin?

down arrow

What is the difference between mutable and immutable in Kotlin?

down arrow

What is the difference between val and final var?

down arrow
Read More