Scala Variables and Data Types

Category : Scala | Sub Category : Scala Programs | By Prasad Bonam Last updated: 2023-10-10 04:21:57 Viewed : 274


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):

  1. Mutable Variable (var):

    scala
    var counter = 0 // Mutable variable counter = 1 // Variable value can be changed

    Mutable variables can be changed after they are initialized.

  2. Immutable Variable (val):

    scala
    val 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:

  1. Numeric Types:

    • Integers:

      scala
      val age: Int = 30
    • Floating-Point Numbers:

      scala
      val price: Double = 19.99
    • BigInt and BigDecimal (for Arbitrary Precision):

      scala
      val bigValue: BigInt = BigInt("1234567890123456789012345678901234567890") val bigDecimalValue: BigDecimal = BigDecimal("1234.56789012345678901234567890")
  2. Characters and Strings:

    • Characters (Char):

      scala
      val firstLetter: Char = `A`
    • Strings (String):

      scala
      val greeting: String = "Hello, Scala!"
  3. Booleans:

    scala
    val isTrue: Boolean = true val isFalse: Boolean = false
  4. Collections:

    Scala provides various collections, including Lists, Sets, Maps, and more. Here is an example with a List:

    scala
    val fruits: List[String] = List("Apple", "Banana", "Orange")
  5. Tuples:

    Tuples allow you to group multiple values of different types:

    scala
    val person: (String, Int) = ("Alice", 30) val (name, age) = person
  6. Option:

    The Option type is used to represent values that might be absent (null in other languages):

    scala
    val maybeValue: Option[Int] = Some(42) val absentValue: Option[Int] = None

    Some represents a value, while None represents absence.

  7. Custom Types (Case Classes):

    You can define custom data types using case classes:

    scala
    case class Person(name: String, age: Int) val alice = Person("Alice", 30)
  8. Enums (Enumerations):

    Scala 3 introduces enums to define a fixed set of values:

    scala
    enum 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.

Search
Related Articles

Leave a Comment: