Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-10 04:21:57 Viewed : 621
In Scala, you can define variables using either var
(mutable variables) or val
(immutable variables). Scala also has a rich set of data types. Here are examples of variables and data types in Scala:
Variables (var
and val
):
Mutable Variable (var
):
scalavar counter = 0 // Mutable variable counter = 1 // Variable value can be changed
Mutable variables can be changed after they are initialized.
Immutable Variable (val
):
scalaval pi = 3.14159 // Immutable variable // pi = 3.14 // Error: Reassignment to val is not allowed
Immutable variables cannot be reassigned once they are initialized. This encourages functional programming and safer code.
Data Types:
Scala has various data types, including numeric types, characters, strings, booleans, and more. Here are some examples:
Numeric Types:
Integers:
scalaval age: Int = 30
Floating-Point Numbers:
scalaval price: Double = 19.99
BigInt and BigDecimal (for Arbitrary Precision):
scalaval bigValue: BigInt = BigInt("1234567890123456789012345678901234567890") val bigDecimalValue: BigDecimal = BigDecimal("1234.56789012345678901234567890")
Characters and Strings:
Characters (Char
):
scalaval firstLetter: Char = `A`
Strings (String
):
scalaval greeting: String = "Hello, Scala!"
Booleans:
scalaval isTrue: Boolean = true val isFalse: Boolean = false
Collections:
Scala provides various collections, including Lists, Sets, Maps, and more. Here is an example with a List:
scalaval fruits: List[String] = List("Apple", "Banana", "Orange")
Tuples:
Tuples allow you to group multiple values of different types:
scalaval person: (String, Int) = ("Alice", 30) val (name, age) = person
Option:
The Option
type is used to represent values that might be absent (null in other languages):
scalaval maybeValue: Option[Int] = Some(42) val absentValue: Option[Int] = None
Some
represents a value, while None
represents absence.
Custom Types (Case Classes):
You can define custom data types using case classes:
scalacase class Person(name: String, age: Int) val alice = Person("Alice", 30)
Enums (Enumerations):
Scala 3 introduces enums to define a fixed set of values:
scalaenum Color: case Red, Green, Blue val color: Color = Color.Green
These are some of the commonly used data types and variable declarations in Scala. Scala is a statically typed language, so you typically specify the data type explicitly when declaring variables. However, Scalas type inference can often infer types, so you dont always need to provide explicit type annotations.