Kotlin Tip #1: Prefer val over var — 100 Kotlin Tips in 100 days

Raphael De Lio
Kotlin with Raphael De Lio
2 min readFeb 10, 2024

Twitter | LinkedIn | YouTube | Instagram

Even though val and var are both valid ways of declaring variables in Kotlin, the first is used for declaring immutable variables while the latter is used for declaring mutable variables.

If you try to run the code above, you will see that it won't compile, and the compiler will return: val cannot be reassigned.

Even though age could be reassigned, name cannot, it's immutable. And you may wonder: wouldn't it be easier to keep my variables mutable and flexible to be changed during development?

Easier to reason about

First of all, in large codebases, knowing that a variable is immutable and that it cannot be reassigned makes it easier to reason over hundreds of lines of code.

To illustrate it, we can define a Book data class with the properties name and author. By defining these properties as immutable, we can be confident that by the time we reach the third method doAThirdThingWithTheBook() the properties of this object will still be the same; in other words, no other function will have changed the state of this object.

Thread-safe

Besides that, it also makes your code thread-safe. By adapting the previous example, but running all the functions in parallel, we can also be confident that these functions won’t interfere with the result of one another. This is because the properties of Book are immutable. None of the functions change its state and therefore none of them will be affected by the others.

Encourages functional programming

In functional programming, we often work with immutable data and pure functions — functions that always produce the same output given the same input and have no side effects (i.e., they don’t modify any external state). This leads to a core that is more predictable, easier to test, and often simpler to reason about.

I hope you have enjoyed the first tip! Don’t forget to subscribe and stay tuned for the upcoming Kotlin tips!

Tip #2: Leverage String Templates

Contribute

Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio

Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw

Follow Me on Social Media

Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.

Twitter | LinkedIn | YouTube | Instagram

--

--