Scala Tutorial
Basics
Control Statements
OOP Concepts
Parameterized - Type
Exceptions
Scala Annotation
Methods
String
Scala Packages
Scala Trait
Collections
Scala Options
Miscellaneous Topics
Literals refer to fixed values in source code that can be assigned to variables or constants. In Scala, as in most programming languages, there are different types of literals corresponding to various data types.
Here's an overview of Scala literals:
Integer Literals
42
0x2A
052
(Scala 2 only; removed in Scala 3)Long Literals
L
or l
makes the integer a Long: 42L
Floating Point Literals
3.14
3.14D
or 3.14d
3.14F
or 3.14f
Character Literals
'a'
'\n'
(newline), '\t'
(tab), '\''
(single quote), '\\'
(backslash)String Literals
"Hello, World!"
"This is a \"quote\"."
"""This is a raw string. It spans multiple lines."""
Boolean Literals
true
and false
Symbol Literals
'symbolName
Multi-line Strings and String Interpolation
s
interpolator.val name = "Alice" val age = 30 val multiLine = s"""Name: $name |Age: $age""".stripMargin
Null Literal
null
(Note: Using null
is discouraged in functional programming. Options or other monadic constructs are preferred.)Function Literals (Lambda Functions)
val add = (x: Int, y: Int) => x + y
In addition to these, Scala 3 introduces new literal types and some changes, especially with string interpolation, pattern matching, and the new optional braces syntax. It's always a good idea to consult the specific version's documentation to understand the nuances.
Scala Literal Types:
Literal types in Scala represent values directly, as opposed to types that represent sets of values.
val myNumber: 42 = 42
Numeric Literals in Scala:
Numeric literals represent numbers in various formats.
val integerLiteral: Int = 42 val floatingPointLiteral: Double = 3.14
String Literals in Scala:
String literals represent sequences of characters.
val myString: String = "Hello, Scala!"
Boolean Literals in Scala:
Boolean literals represent the logical values true
or false
.
val myBoolean: Boolean = true
Character Literals in Scala:
Character literals represent single characters enclosed in single quotes.
val myChar: Char = 'A'
Symbol Literals in Scala:
Symbol literals represent unique identifiers and are written as '<identifier>
.
val mySymbol: Symbol = 'mySymbol
Literal Values vs Variables in Scala:
Literal values are fixed and cannot be changed, while variables can be reassigned.
val literalValue: Int = 42 var myVariable: Int = 42 // This will result in a compilation error // literalValue = 43 // This is valid myVariable = 43
Literal Interpretation in Scala:
Scala provides a way to interpret string literals with the s
, f
, and raw
interpolators.
val name = "Alice" val greeting = s"Hello, $name!"
The s
interpolator allows variable substitution within the string.