Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Basic Types







Introduction to Basic Types in Scala

  • Overview: Scala integrates object-oriented and functional programming in a statically typed language. Unlike Java, Scala treats all types as objects.
  • Type Hierarchy: Explanation of Scala's type hierarchy, with Any at the top, splitting into AnyVal (value types) and AnyRef (reference types).
  • Immutability: Emphasizes Scala's preference for immutable types to promote functional programming practices.







Numeric Types

Int

  • Range: -2^31 to 2^31-1
  • Use: Default integer type for general numerical computation.
  • Example: val i: Int = 123456

Long

  • Range: -2^63 to 2^63-1
  • Use: Storing large integer values.
  • Example: val l: Long = 12345678910L

Double

  • Precision: 64-bit IEEE 754 floating-point.
  • Use: Default type for floating-point numbers, for double-precision decimals.
  • Example: val d: Double = 123.456







Character and Boolean Types

  1. Char
  • Description: Represents a single 16-bit Unicode character.
  • Use: Storing characters or small character-based data.
  • Example: val c: Char = 'A'
  1. Boolean
  • Description: Represents a logical value, either true or false.
  • Use: Controlling flow with conditional statements, logical operations.
  • Example: val flag: Boolean = true







String Type

  • String
    • Description: A sequence of characters. In Scala, String is equivalent to java.lang.String, fully supported with additional Scala-specific methods.
    • Use: Storing and manipulating text data.
    • Example: val str: String = "Hello, Scala!"







Unit, Null, and Nothing Types

  1. Unit
  • Equivalent to void in Java. Represents a method that does not return a meaningful value.
  • Example: def myFunction(): Unit = { println("This function returns no meaningful value") }
  1. Null
  • Represents the absence of a value for reference types. It is a subtype of all reference types (AnyRef), not value types.
  • Example: var str: String = null
  1. Nothing
  • A subtype of every other type; used to indicate abnormal termination or a program location that must not be reached.