Home »
Scala
Scala Literals
By IncludeHelp Last updated : October 07, 2024
What are Scala Literals?
In Scala, the literals are the set of values / symbols used for defining a constant in the code (Or, we can say that, a literal is a value that can be assigned to a variable. Literals are basic constants that are assigned to the variable.). There are many types of literals including the values, symbols, special characters.
Types of Scala Literals
A literal is a value that can be assigned to a variable. Literals are basic constants that are assigned to the variable.
- Integer Literals
- Float Literals
- Character Literals
- String Literals
- Boolean Literals
1) Integer Literals
Literals of type int or type Long. Integer literals can be declared using suffix L or I.
Example
Decimal Literal:
var i = 10L
Hexadecimal Literal:
var I = 0xFFF
2) Float Literals
Literals of type float or type double. They use Suffix f/F for float and D/d for double.
Example
Float Literal:
var i = 12.35f
Double Literal:
var I = 123.5445d
3) Character Literals
The character literals are the single characters written in single quotes ' '.
Example
val char_value = 'T'
val arrow_code = '\u2191'
4) String Literals
The string literals are the sequence of characters written in double quotes " or triple double quotes """. There are two types of strings literals: Single-line and multi-line string literals. The single-line string literal is written in double quotes ", while multi-line string literals are written in triple double quotes """.
Example
Single-line string literal:
val message = "Hello, world!"
Multi-line string literal:
"Include Help
is of the best
Programming tutor"
5) Boolean Literals
A literal with any of two values, True/False.
Example
val var1 = true
val var2 = false
Scala code to demonstrate the example of literals
object MyClass {
def main(args: Array[String]): Unit = {
// Integer Literals
val x = 41
val y = 0x1f // hexadecimal
// Float Literal
val pi = 31415e-4d
// Boolean Literals
val var1 = true
val var2 = false
// Character Literals
val anyChar = 'X'
val arrowUnicode = '\u2191'
// String Literals
var str1 = "Hello, world!"
var str2 = """India,
USA,
UK"""
// printing the values
println("x = " + x)
println("y = " + y)
println("var1 = " + var1)
println("anyChar = " + anyChar)
println("arrowUnicode = " + arrowUnicode)
println("str1 = " + str1)
println("str2 = " + str2)
}
}
Output
x = 41
y = 31
var1 = true
anyChar = X
arrowUnicode = ↑
str1 = Hello, world!
str2 = India,
USA,
UK