Introduction to Scala Variables
After you have created your own Scala project, you can begin to write code. In this short article, we are going to learn how to use and set Scala variables.
How to set Scala Variables?
If you want to declare a variable, you must use the keyword
var variableName = 12
This line will declare a variable named
How to set Scala Values?
In Scala, we prefer to use
variables. You can read why on StackOverflow.
This is how you declare a value:
val valueName = 12
This line will declare a value named
How to declare the Type?
Variables will have a type inferred by the compiler. If you would like to add a type to your variable, you must use the
val name: String = "leo"
In Scala, everything can be assigned to a value:
- integers, strings, …
- lambda functions
We are going to talk more about the above in upcoming articles.
What is the keyword
You might have seen the keyword
lazy val complexMath: Double = 10 * 10 * 10
In this instance, I am going to use
as an example of a value. We could imagine this value as being long and costly to calculate.
With the keyword
‘s value will only be computed once when used for the very first time.
The code used to generate
‘s value will not be executed until it used for the first time.
Also, the value generated, in this case
, will be stored and the code used to generate this value will not be executed again a second time.
Let’s go through a short example to practice what we have learned.
Feel free to play with it.
If the playground above does not load, you can go directly to Scastie.
What to remember?
A few things to remember about Scala variables:
- Use immutable as much as possible and avoid using mutable
- Syntax is
val <name>:<type> = <value>
lazywill delay the evaluation of the value to the first use
By understanding these basics, you should now be able to declare and use variables in Scala code.
Feel free to leave comments if you have any questions.