Cover by Alex Payne, Dean Wampler

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Literals

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

Integer literals can be expressed in decimal, hexadecimal, or octal. The details are summarized in Table 2-1.

Table 2-1. Integer literals

KindFormatExamples

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 typeMinimum (inclusive)Maximum (inclusive)

Long

−263

263 − 1

Int

−231

231 − 1

Short

−215

215 − 1

Char

0

216 − 1

Byte

−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 = ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required