What you’ll learn in this blog post -
- How to declare immutables and variables in Scala.
- How to define functions in Scala.
A val is a way of declaring immutables in Scala. By immutable, I mean that the value of a variable cannot be modified or changed after the declaration. As a result of this constraint, you’ve to initialize a val when you declare it.
A few notes on val -
A val is more easier to read and understand as it is always initialized at the time of declaration.
A val is more safer - you don’t have to worry if some other part of your code is changing it. This becomes even more important in multi-threaded systems.
Due to the functional nature of Scala and also due to Pattern Matching, I believe vals are more commonly used than vars.
Although you cannot change the value of a val, you should be able to change the state of a val object.
A var is a way of declaring mutables (or variables) in Scala.
A few notes on vars -
- The main drawbacks of val is that for some scenarios, it is not intuitive to use vals. It would be a lot easier to use vars.
Consider the following example, to note this difference
In Scala, def is a way to define a function. More about functions in this gist -
One of the useful features of functions in Scala is that the arguments can take default values. Here’s how you can define them -
Code. Learn. Explore