Often, a new object is
initialized with a literal value, such as
val book = "Programming Scala"
. Let’s discuss the kinds
of literal values supported by Scala. Here, we’ll limit ourselves to
lexical syntax literals. We’ll cover literal syntax for functions (used as
values, not member methods), tuples, and certain
types like Lists
and Maps
as we come
to them.
Integer literals can be expressed in decimal, hexadecimal, or octal. The details are summarized in Table 2-1.
Table 2-1. Integer literals
Kind | Format | Examples |
---|---|---|
Decimal | 0 or a nonzero digit followed by zero or more digits (0–9) | 0, 1, 321 |
Hexadecimal | 0x followed by one or more hexadecimal digits (0–9, A–F, a–f) | 0xFF, 0x1a3b |
Octal | 0 followed by one or more octal digits (0–7) | 013, 077 |
For Long
literals, it is necessary to append the L
or
l
character at the end of the literal. Otherwise, an
Int
is used. The valid values for an integer literal
are bounded by the type of the variable to which the value will be
assigned. Table 2-2 defines the
limits, which are inclusive.
Table 2-2. Ranges of allowed values for integer literals (boundaries are inclusive)
Target type | Minimum (inclusive) | Maximum (inclusive) |
---|---|---|
| −263 | 263 − 1 |
| −231 | 231 − 1 |
| −215 | 215 − 1 |
| 0 | 216 − 1 |
| −27 | 27 − 1 |
A compile-time error occurs if an integer literal number is specified that is outside these ranges, as in the following examples:
scala > val i = 12345678901234567890 <console>:1: error: integer number too large val i = 12345678901234567890 scala> val b: Byte = ...
No credit card required