Data Types
Prerequisites: Values and variables
Every value in Scala has a type. The basic types are:
| Type | Holds | Example |
|---|---|---|
Int |
whole numbers (32-bit) | 42 |
Long |
large whole numbers (64-bit) | 9000000000L |
Double |
decimal numbers | 3.14 |
Boolean |
true or false |
true |
Char |
a single character | 'A' |
String |
text | "hello" |
Unit |
"no useful value" | () |
@main def types(): Unit =
val count: Int = 42
val population: Long = 8_100_000_000L
val price: Double = 19.99
val isOpen: Boolean = true
val grade: Char = 'A'
val name: String = "Ada"
println(s"$count $population $price $isOpen $grade $name")
println(Int.MaxValue)
println(Int.MaxValue + 1)
42 8100000000 19.99 true A Ada
2147483647
-2147483648
- Underscores make long numbers readable:
8_100_000_000L. Lmarks aLongliteral.Inthas limits: going pastInt.MaxValuewraps around to a negative number silently. UseLongorBigIntfor large values.
Everything is an object
Even numbers have methods:
@main def methodsOnValues(): Unit =
println((-5).abs)
println(3.max(7))
println(10.toDouble)
println(3.99.toInt)
println('a'.toUpper)
println("42".toInt + 1)
5
7
10.0
3
A
43
Converting with toInt on a Double truncates (3.99 → 3). Converting
a String that isn't a number throws an error — the Option lesson shows
the safe way.
The type hierarchy
At the top is Any. Below it, AnyVal covers values like Int and
Boolean, and AnyRef covers objects like String and List. At the
bottom, Nothing is the type of expressions that never return (like
throwing an exception).