Scala Literals

A literal is a data that appears directly in the source code. There are many types of literals in Scala such as Integral Literals, Character Literals, Floating-Point Literal, Symbol Literals, Boolean Literals, String Literals, and so on.

The following are the Literals supported in Scala.

    1. Integral Literals

    The type of integer literals is Int or long and the range of Int between −231−231 and 231−1231−1 and the range of Long is between 263−263 and 263−1263−1. In case an integer is going beyond this range then an exception is thrown.

    integerLiteral ::= (decimalNumeral | hexNumeral) [‘L’ | ‘l’] decimalNumeral ::= ‘0’ | nonZeroDigit {digit} hexNumeral ::= ‘0’ (‘x’ | ‘X’) hexDigit {hexDigit} digit ::= ‘0’ | nonZeroDigit nonZeroDigit ::= ‘1’ | … | ‘9’

    2. Character Literals

    The type of character literal is a character that is enclosed in quotes. now the character can be a printable Unicode character or it can be an escape sequence.

    'a' '\u0041' '\n' '\t'

    3. Floating Point Literal

    The type of Floating-point literals is Float. It has a suffix of F or f. The float has a 754 32-bit single-precision floating value.

    1e30f 3.14159f 1.0e100

    4. Symbol Literals

    In Scala, the symbol is case class and represented as a shorthand for the expression scala.Symbol("x").

    package scala final case class Symbol private (name: String) { override def toString: String = "'" + name }

    5. Boolean Literals

    The type of boolean literals is presented as true and false type boolean values.

    booleanLiteral ::= ‘true’ | ‘false’

    6. String Literals

    The type of string literal is a sequence of character which is mentioned in double-quotes. In case there is a double quote in string literals then that should be escaped with "\"".

    "Hello, \nScala" "This is String Literals \" example"

    7. Multi-Line Strings

    The type of multi-line string literal is the sequence of character which are mentioned in three quotes """...""".

    """ This is Scala Basic Literals example """

    8. Null Values

    Null Value is compatible with every reference type because its type is scala.Null.

Scala Escape Sequences

The following is the list of Escape Sequences that are used in character and string literals.

Escape Sequences Unicode Description
\b \u0008 backspace BS
\t \u0009 horizontal tab HT
\n \u000c formfeed FF
\f \u000c formfeed FF
\r \u000d carriage return CR
\" \u0022 double quote "
\' \u0027 single quote .
\\ \u005c backslash \

A simple program to print "Hello World, This is Scala simple program" using \n escape sequence.