Scala Literal Types
Literal:
A literal is a way to write a constant value directly in code.
Types of Literals in Scala:
There are six types of literals in Scala, these are:
Integer literals:
This type of literals for the types Int, Long, Short, and Byte come in three forms: decimal, hexadecimal, and octal. The way an integer literal begins indicates the base of the number. If the number begins with a 0x or 0X, it
is hexadecimal (base 16), and may contain 0 through 9 as well as upper or lowercase digits A through F.
Example:
scala> val hex = 0x5 hex: Int = 5 scala> val hex2 = 0x00FF hex2: Int = 255 scala> val magic = 0xcafebabe magic: Int = 889275714
Floating-point literals: This type of literals are made up of decimal digits, optionally containing a decimal point, and optionally followed by an E or e and an exponent.
Example:
scala> val big = 1.2345 big: Double = 1.2345 scala> val bigger = 1.2345e1 bigger: Double = 12.345 scala> val biggerStill = 123E45 biggerStill: Double = 1.23E47
Character literals: These literals are composed of any Unicode character between a single
quotes, such as:
scala> val a = 'A' a: Char = A
In addition to providing an explicit character between the single quotes, you can provide an octal or hex number for the character code point preceded by a backslash. The octal number must be between ‘\0’ and ‘\377’.
Example:
scala> val c = '\101' c: Char = A
There is some Special character literal escape sequences are given below:
\n - line feed (\u000A) \b - backspace (\u0008) \t - tab (\u0009) \f - form feed (\u000C) \r - carriage return (\u000D) \" - double quote (\u0022) \' - single quote (\u0027) \\ - backslash (\u005C)
String literals: A string literal is composed of characters surrounded by double quotes:
scala> val hello = "hello" hello: java.lang.String = hello
The syntax of the characters within the quotes is the same as with the character literals.
Example:
scala> val escapes = "\\\"\'" escapes: java.lang.String = \"'
Symbol literals: A symbol literal is written ‘ident, where ident can be any alphanumeric identifier. Such literals are mapped to instances of the predefined class scala. Symbol. Specifically, the literal ‘cymbal will be expanded by the compiler to a factory method invocation: Symbol(“cymbal”). Symbol literals are typically used in situations where you would use just an identifier in a dynamically typed language. For instance, you might want to define a method that updates a record in a database:
scala> def updateRecordByName(r: Symbol, value: Any) { // code goes here } updateRecordByName: (Symbol,Any)Unit
Boolean literals: The Boolean type has two literals, true and false:
scala> val bool = true bool: Boolean = true scala> val fool = false fool: Boolean = false