Strings and Other Literals
In the following lesson, you will be introduced to literals.
We'll cover the following...
By now, you must have noticed that we haven’t discussed strings. Strings do not fall under anyVal in the data type hierarchy. This raises the question: what are strings?
The single word answer is ‘literals’.
Literals
A literal is defined as taking anything in its most usual and basic sense. Mapping this onto computer programming, literals are fixed values appearing directly as is in the source code. For example, “Hello World”, , and ‘A’ are all literals.
String Literals
Strings literals are a combination of characters surrounded by double quotation marks. The syntax for declaring a variable of type String is the same as declaring a variable of any basic value type.
Integer Literals
Integer Literals are used with the value types Long, Int, Short, and Byte and come in two forms: decimal and hexadecimal. Decimal numbers have a base while hexadecimal numbers have a base . The way an integer literal begins indicates the base of the number. If the number begins with a x or X, it is hexadecimal and may contain the numbers from through as well as upper or lowercase letters from A to F. Numbers that do not start with x or X are decimal by default.
One thing to remember is that Scala will always print an integer literal as decimal regardless of how it is declared.
Floating-Point Literals
Floating-point literals are used with Double and Float. They are made up of decimal digits and have the option of adding exponents using either an e or E followed by the exponent.
Character Literals
Character literals are used with Char and are made up of a single Unicode character surrounded by single quotation marks.
Escape sequences, as shown in the table below, also represent character literals.
| Literal | Meaning |
|---|---|
| \n | linefeed |
| \b | backspace |
| \t | tab |
| \f | form feed |
| \r | carriage return |
| \" | double quote |
| \’ | single quote |
| \\ | backslash |
Let’s look at some examples:
Boolean Literals
Boolean literals are used with Boolean. They are of two types: true and false.
Let’s complete our discussion on variables and types with type inference in the next lesson.