Scala Variables & Data Types
Learn about vals, vars, and Scala's type system.
Variable Declaration
Scala has two types of variables:
- val - Immutable (cannot be reassigned)
- var - Mutable (can be reassigned)
val name = "Alice" // Immutable
var age = 25 // Mutable
name = "Bob" // Error: reassignment to val
age = 26 // OK
Type Inference
Scala has strong type inference. You don't always need to specify types explicitly:
val greeting = "Hello" // Type inferred as String
val count = 5 // Type inferred as Int
val pi = 3.14159 // Type inferred as Double
You can explicitly declare types if needed:
val greeting: String = "Hello"
val count: Int = 5
val pi: Double = 3.14159
Basic Data Types
Scala has the same basic types as Java but treats them as objects:
Type | Description | Example |
---|---|---|
Byte | 8-bit signed integer | val b: Byte = 127 |
Short | 16-bit signed integer | val s: Short = 32767 |
Int | 32-bit signed integer | val i = 2147483647 |
Long | 64-bit signed integer | val l = 9223372036854775807L |
Float | 32-bit floating point | val f = 3.14159f |
Double | 64-bit floating point | val d = 3.14159 |
Char | 16-bit Unicode character | val c = 'A' |
Boolean | true or false | val flag = true |
String | Sequence of characters | val str = "Hello" |
Type Hierarchy
Scala has a unified type hierarchy where all types inherit from Any:
Any
├── AnyVal (value types: Int, Double, Boolean, etc.)
└── AnyRef (reference types: all classes, String, List, etc.)
└── Null (subtype of all AnyRef types)
└── Nothing (subtype of all types)
← Back to Tutorials