Scala Tutorial

Values & Variables

val vs var and the importance of immutability in Scala

val vs. var

In Scala, you define values and variables using keywords that clearly indicate whether they can be changed.
  1. val: An immutable value. Once set, it can never be changed. Always prefer val by default.
  2. var: A mutable variable. It can be reassigned later.
scala
val name = "Alpha" // Cannot be changed
var age = 25       // Can be changed
age = 26
Wait! Scala encourages the use of val as much as possible. This "Immutable by Default" philosophy makes your code safer and much easier to parallelize.

Type Inference

Scala has a very smart compiler. You usually don't need to specify the type yourself.
scala
val count = 42 // Scala knows this is an Int
If you want to be explicit (e.g., for public APIs), you can add the type after a colon:
scala
val total: Double = 100.0

Lazy Values

Wait! You can mark a value as lazy. This means it won't be calculated until the very first time it is accessed. This is great for expensive operations or database connections.
scala
lazy val bigData = loadFromDatabase()

Common Types

TypeDescription
Int32-bit signed integer
Long64-bit signed integer
Double64-bit floating point
Booleantrue or false
StringSequence of characters
UnitEquivalent to void

Summary

TermDescription
valImmutable value (The standard)
varMutable variable (Use sparingly)
lazy valValue computed only on first use
AnyThe base type for all types in Scala
AnyValBase type for value types (Int, Double, etc.)
AnyRefBase type for reference types (Objects)
Best ForPredictable and bug-free code
LogicFavor immutability to prevent state-related bugs
SafetyStatic typing with powerful inference
ModernConcise syntax compared to traditional Java
StandardUse camelCase for all values and variables
IdentityEverything in Scala is an object