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
Anyat the top, splitting intoAnyVal(value types) andAnyRef(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
- Char
- Description: Represents a single 16-bit Unicode character.
- Use: Storing characters or small character-based data.
- Example:
val c: Char = 'A'
- Boolean
- Description: Represents a logical value, either
trueorfalse. - Use: Controlling flow with conditional statements, logical operations.
- Example:
val flag: Boolean = true
String Type
- String
- Description: A sequence of characters. In Scala,
Stringis equivalent tojava.lang.String, fully supported with additional Scala-specific methods. - Use: Storing and manipulating text data.
- Example:
val str: String = "Hello, Scala!"
- Description: A sequence of characters. In Scala,
Unit, Null, and Nothing Types
- Unit
- Equivalent to
voidin Java. Represents a method that does not return a meaningful value. - Example:
def myFunction(): Unit = { println("This function returns no meaningful value") }
- 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
- Nothing
- A subtype of every other type; used to indicate abnormal termination or a program location that must not be reached.