In Scala, variables are classified into different types based on their mutability and declaration style. Here are the main types of variables in Scala:
Val (Immutable Variables):
val stands for "value."
Val variables are immutable, which means their values cannot be changed once they are assigned.
They are declared using the val keyword.
Val variables are thread-safe and promote functional programming practices.
val pi: Double = 3.14159
Var (Mutable Variables):
var stands for "variable."
Var variables are mutable, meaning their values can be changed after assignment.
They are declared using the var keyword.
While vars provide flexibility, they should be used with caution to avoid unexpected changes in state.
var count: Int = 0
count = 1 // Valid, the value can be changed
Lazy Val (Lazy Immutable Variables):
lazy val combines the characteristics of both val and lazy constructs.
Lazy val variables are immutable like vals, but their initialization is deferred until first accessed.
They are declared using the lazy val keywords.
Lazy vals are useful for delaying expensive computations until they are needed.
lazy val expensiveResult: Int = {
// Expensive computation
42
}
Mutable Collections (e.g., var mutableList: List[Int] = List(1, 2, 3)):
Collections in Scala, such as lists, sets, and maps, can be mutable or immutable based on how they are declared.
Mutable collections allow adding, removing, and modifying elements after creation.
They are often declared using mutable collection classes like mutable.ListBuffer, mutable.Set, or mutable.Map.
import scala.collection.mutable.ListBuffer
val mutableList: ListBuffer[Int] = ListBuffer(1, 2, 3)
mutableList += 4 // Modifying a mutable collection
Immutable Collections (e.g., val immutableList: List[Int] = List(1, 2, 3)):
Immutable collections, on the other hand, do not allow changes to their content after creation.
They are often declared using immutable collection classes like List, Set, or Map.
val immutableList: List[Int] = List(1, 2, 3)
// immutableList += 4 // This will result in a compilation error
Constants (e.g., final val PI: Double = 3.14159):
Constants are declared using the final val keywords.
They are typically used to define values that should not be changed throughout the program's execution.
Constants should be named in uppercase by convention.
final val PI: Double = 3.14159