Scala Literals
Literals are symbols that directly represent values in source code. This chapter will detail various types of literal representations in Scala.
Integer Literals
Decimal Literals
scala
val decimal1 = 0 // Int
val decimal2 = 123 // Int
val decimal3 = 456789 // Int
// Use underscores to improve readability (Scala 2.13+)
val largeNumber = 1_000_000 // 1000000
val creditCard = 1234_5678_9012_3456LHexadecimal Literals
scala
val hex1 = 0x0 // 0
val hex2 = 0xFF // 255
val hex3 = 0xCAFEBABE // 3405691582
val hex4 = 0x7FFFFFFF // Int.MaxValue
// Case insensitive
val hexLower = 0xcafebabe
val hexUpper = 0xCAFEBABE
val hexMixed = 0xCafeBabeOctal Literals (Scala 3)
scala
// Scala 3 supports octal literals
val octal1 = 0o777 // 511
val octal2 = 0o123 // 83
val octal3 = 0o0 // 0
// Note: Scala 2 does not support 0o prefix octalBinary Literals (Scala 3)
scala
// Scala 3 supports binary literals
val binary1 = 0b1010 // 10
val binary2 = 0b1111 // 15
val binary3 = 0b0 // 0
val binary4 = 0b11111111 // 255
// Use underscore separators
val binaryLarge = 0b1111_0000_1010_1010Long Literals
scala
val long1 = 123L // Long type
val long2 = 456l // Long type (lowercase l, not recommended)
val longHex = 0xFFFFFFFFL
val longMax = 9223372036854775807L // Long.MaxValue
// Large numbers with underscores
val longLarge = 123_456_789_012_345LFloating Point Literals
Double Literals
scala
val double1 = 3.14 // Double
val double2 = 0.0 // Double
val double3 = 1. // 1.0 (Double)
val double4 = .5 // 0.5 (Double)
// Scientific notation
val scientific1 = 1.23e4 // 12300.0
val scientific2 = 1.23E4 // 12300.0
val scientific3 = 1.23e-4 // 0.000123
val scientific4 = 1.23E-4 // 0.000123
// Explicit Double suffix
val explicitDouble = 3.14d // Double
val explicitDouble2 = 3.14D // DoubleFloat Literals
scala
val float1 = 3.14f // Float
val float2 = 3.14F // Float
val float3 = 0.0f // Float
// Scientific notation Float
val floatScientific = 1.23e4f // 12300.0f
val floatScientific2 = 1.23E-4F // 0.000123f
// Special Float values
val floatInfinity = Float.PositiveInfinity
val floatNegInfinity = Float.NegativeInfinity
val floatNaN = Float.NaNSpecial Floating Point Values
scala
// Positive infinity
val posInf = Double.PositiveInfinity
val posInfFloat = Float.PositiveInfinity
// Negative infinity
val negInf = Double.NegativeInfinity
val negInfFloat = Float.NegativeInfinity
// Not a Number
val nan = Double.NaN
val nanFloat = Float.NaN
// Check special values
val isInfinite = posInf.isInfinite // true
val isNaN = nan.isNaN // true
val isFinite = 3.14.isFinite // trueCharacter Literals
Basic Character Literals
scala
val char1 = 'A' // Character A
val char2 = 'z' // Character z
val char3 = '0' // Character 0
val char4 = ' ' // Space character
val char5 = '中' // Chinese characterEscape Character Literals
scala
val tab = '\t' // Tab character
val newline = '\n' // Newline character
val carriageReturn = '\r' // Carriage return
val backslash = '\\' // Backslash
val singleQuote = '\'' // Single quote
val doubleQuote = '\"' // Double quote
val backspace = '\b' // Backspace
val formFeed = '\f' // Form feedUnicode Character Literals
scala
val unicodeA = '\u0041' // 'A' (Unicode)
val unicodeHeart = '\u2764' // ❤ (heart symbol)
val unicodeSmiley = '\u263A' // ☺ (smiley)
val unicodeChinese = '\u4E2D' // 中
// Print Unicode characters
println(s"Heart: $unicodeHeart")
println(s"Smiley: $unicodeSmiley")
println(s"Chinese: $unicodeChinese")Octal Character Literals
scala
val octalChar1 = '\101' // 'A' (octal 101 = decimal 65)
val octalChar2 = '\141' // 'a' (octal 141 = decimal 97)
val octalChar3 = '\0' // null characterString Literals
Regular String Literals
scala
val str1 = "Hello, World!"
val str2 = "Scala is awesome"
val str3 = "" // Empty string
val str4 = "String containing Chinese characters"
// Strings with escape characters
val escaped = "Line 1\nLine 2\tTabbed text"
val quoted = "He said \"Hello\" to me"
val path = "C:\\Users\\username\\Documents"Raw String Literals
Use triple double quotes to create raw strings without escaping:
scala
val rawString = """This is a raw string.
It can contain "quotes" and \backslashes
without escaping them."""
val sqlQuery = """
SELECT name, age, email
FROM users
WHERE age > 18
AND active = true
ORDER BY name
"""
val regexPattern = """^\d{3}-\d{2}-\d{4}$""" // Regular expression
// Use stripMargin to handle indentation
val formattedString = """
|This is line 1
|This is line 2
|This is line 3
""".stripMargin
// Custom margin character
val customMargin = """
#This uses # as margin
#Instead of |
#Very flexible
""".stripMargin('#')String Interpolation Literals
s Interpolator
scala
val name = "Alice"
val age = 25
val height = 5.6
// Basic interpolation
val basic = s"Name: $name, Age: $age"
// Expression interpolation
val expression = s"Next year $name will be ${age + 1} years old"
val calculation = s"Area: ${math.Pi * 2 * 2}"
// Method call interpolation
val upper = s"Uppercase name: ${name.toUpperCase}"f Interpolator (Formatting)
scala
val pi = math.Pi
val e = math.E
// Floating point formatting
val formatted1 = f"Pi: $pi%.2f" // "Pi: 3.14"
val formatted2 = f"E: $e%.4f" // "E: 2.7183"
// Integer formatting
val number = 42
val formatted3 = f"Number: $number%05d" // "Number: 00042"
// String formatting
val text = "hello"
val formatted4 = f"Text: $text%10s" // "Text: hello"
val formatted5 = f"Text: $text%-10s" // "Text: hello "raw Interpolator
scala
val path = raw"C:\Users\$name\Documents"
// Result: "C:\Users\Alice\Documents" (backslashes not escaped)
val regex = raw"\d+\.\d+" // Regular expression, no need to double escape
val windowsPath = raw"D:\Projects\Scala\src\main\scala"Custom Interpolator
scala
// Define custom interpolator
implicit class JsonInterpolator(val sc: StringContext) extends AnyVal {
def json(args: Any*): String = {
val strings = sc.parts.iterator
val expressions = args.iterator
val buf = new StringBuilder(strings.next())
while (strings.hasNext) {
buf.append(expressions.next())
buf.append(strings.next())
}
buf.toString
}
}
// Use custom interpolator
val key = "name"
val value = "Alice"
val jsonString = json"""{"$key": "$value"}"""
// Result: """{"name": "Alice"}"""Boolean Literals
scala
val isTrue = true // Boolean true
val isFalse = false // Boolean false
// Boolean operations
val and = true && false // false
val or = true || false // true
val not = !true // false
// Use in conditional expressions
val result = if (isTrue) "yes" else "no"
val status = if (isFalse) "inactive" else "active"Symbol Literals
Symbols are immutable strings, often used as identifiers:
scala
val symbol1 = Symbol("name") // Full form
val symbol2 = 'name // Short form (deprecated)
// Use of symbols
val symbols = Map(
Symbol("firstName") -> "Alice",
Symbol("lastName") -> "Smith",
Symbol("age") -> 25
)
val firstName = symbols(Symbol("firstName"))Array Literals
scala
// Array literals
val intArray = Array(1, 2, 3, 4, 5)
val stringArray = Array("a", "b", "c")
val mixedArray = Array(1, "hello", true, 3.14)
// Empty array
val emptyIntArray = Array.empty[Int]
val emptyStringArray = Array[String]()
// Array of specified size
val zeroArray = Array.fill(5)(0) // Array(0, 0, 0, 0, 0)
val rangeArray = Array.range(1, 6) // Array(1, 2, 3, 4, 5)Collection Literals
List Literals
scala
val list1 = List(1, 2, 3, 4, 5)
val list2 = List("a", "b", "c")
val emptyList = List()
val nilList = Nil
// Use cons operator
val consList = 1 :: 2 :: 3 :: Nil // List(1, 2, 3)
val prependList = 0 :: list1 // List(0, 1, 2, 3, 4, 5)Set Literals
scala
val set1 = Set(1, 2, 3, 2, 1) // Set(1, 2, 3) - deduplication
val set2 = Set("apple", "banana", "cherry")
val emptySet = Set.empty[String]Map Literals
scala
val map1 = Map("a" -> 1, "b" -> 2, "c" -> 3)
val map2 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val emptyMap = Map.empty[String, Int]
// Use tuple syntax
val map3 = Map(("x", 10), ("y", 20), ("z", 30))Vector Literals
scala
val vector1 = Vector(1, 2, 3, 4, 5)
val vector2 = Vector("hello", "world")
val emptyVector = Vector.empty[Double]Tuple Literals
scala
val tuple2 = (1, "hello") // Tuple2[Int, String]
val tuple3 = (1, "hello", true) // Tuple3[Int, String, Boolean]
val tuple4 = (1, 2.0, "three", false) // Tuple4[Int, Double, String, Boolean]
// Nested tuples
val nested = ((1, 2), ("a", "b")) // ((Int, Int), (String, String))
// Single element tuple (need comma)
val singleTuple = (42,) // Tuple1[Int]Function Literals
scala
// Anonymous function literals
val add = (x: Int, y: Int) => x + y
val square = (x: Int) => x * x
val isEven = (x: Int) => x % 2 == 0
// Simplified syntax
val double = (_: Int) * 2
val increment = (_: Int) + 1
// Multi-parameter simplified
val sum = (_: Int) + (_: Int)
// No-argument function
val random = () => scala.util.Random.nextInt(100)Regular Expression Literals
scala
// Create regular expressions using r method
val emailRegex = """[\w\.-]+@[\w\.-]+\.\w+""".r
val phoneRegex = """\d{3}-\d{3}-\d{4}""".r
val dateRegex = """\d{4}-\d{2}-\d{2}""".r
// Use regular expressions
val email = "user@example.com"
val isValidEmail = emailRegex.matches(email)
val text = "Call me at 123-456-7890"
val phoneNumbers = phoneRegex.findAllIn(text).toListSpecial Literals
Unit Literals
scala
val unit1 = () // The only value of Unit type
val unit2: Unit = {} // Empty code block also returns Unit
def sideEffect(): Unit = {
println("This has side effects")
() // Explicitly return Unit
}Null Literals
scala
val nullValue: String = null // Not recommended
val nullList: List[Int] = null // Not recommended
// Recommend using Option instead of null
val optionalValue: Option[String] = None
val someValue: Option[String] = Some("hello")Practical Application Examples
Configuration File Parsing
scala
object ConfigParser {
// Use various literals to define configuration
val defaultConfig = Map(
"server.port" -> 8080,
"server.host" -> "localhost",
"database.url" -> "jdbc:postgresql://localhost:5432/mydb",
"database.username" -> "user",
"database.password" -> "password",
"app.debug" -> true,
"app.version" -> "1.0.0",
"app.timeout" -> 30.0
)
// Use raw strings to define SQL
val createUserTable = """
|CREATE TABLE users (
| id SERIAL PRIMARY KEY,
| name VARCHAR(100) NOT NULL,
| email VARCHAR(255) UNIQUE NOT NULL,
| created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|)
""".stripMargin
// Use string interpolation to generate dynamic SQL
def findUserByEmail(email: String): String = {
s"""
|SELECT id, name, email, created_at
|FROM users
|WHERE email = '$email'
""".stripMargin
}
}Data Validation
scala
object Validators {
// Regular expression literals
val emailRegex = """^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$""".r
val phoneRegex = """^\+?1?[-.\s]?\(?(\d{3})\)?[-.\s]?(\d{3})[-.\s]?(\d{4})$""".r
val zipCodeRegex = """^\d{5}(-\d{4})?$""".r
// Validation functions
def validateEmail(email: String): Boolean = {
emailRegex.matches(email)
}
def validatePhone(phone: String): Boolean = {
phoneRegex.matches(phone)
}
def validateZipCode(zip: String): Boolean = {
zipCodeRegex.matches(zip)
}
// Test data
val testEmails = List(
"user@example.com",
"invalid.email",
"test@domain.co.uk"
)
val testPhones = List(
"123-456-7890",
"(123) 456-7890",
"1234567890"
)
}Exercises
Exercise 1: Literal Recognition
scala
object LiteralExercise {
// Identify the types of the following literals
val mystery1 = 42 // Int
val mystery2 = 42L // Long
val mystery3 = 3.14f // Float
val mystery4 = 3.14 // Double
val mystery5 = 'A' // Char
val mystery6 = "Hello" // String
val mystery7 = true // Boolean
val mystery8 = () // Unit
val mystery9 = 0xFF // Int (255)
val mystery10 = 1.23e-4 // Double
def printTypes(): Unit = {
println(s"mystery1: ${mystery1.getClass.getSimpleName}")
println(s"mystery2: ${mystery2.getClass.getSimpleName}")
println(s"mystery3: ${mystery3.getClass.getSimpleName}")
// ... Continue printing other types
}
}Exercise 2: String Interpolation Application
scala
object StringInterpolationExercise {
case class Product(name: String, price: Double, quantity: Int)
val products = List(
Product("Laptop", 999.99, 5),
Product("Mouse", 29.99, 20),
Product("Keyboard", 79.99, 15)
)
def generateReport(): String = {
val header = "Product Inventory Report"
val separator = "=" * header.length
val reportLines = products.map { product =>
f"${product.name}%-15s ${product.price}%8.2f ${product.quantity}%5d ${product.price * product.quantity}%10.2f"
}
s"""
|$header
|$separator
|${"Product"}%-15s ${"Price"}%8s ${"Qty"}%5s ${"Total"}%10s
|${"-" * 50}
|${reportLines.mkString("\n")}
|${"-" * 50}
|Total Value: ${f"${products.map(p => p.price * p.quantity).sum}%.2f"}
""".stripMargin
}
def main(args: Array[String]): Unit = {
println(generateReport())
}
}Summary
This chapter detailed various literals in Scala:
- Numeric literals: Various representations of integers and floating point numbers
- Character literals: Characters, escape characters, Unicode characters
- String literals: Regular strings, raw strings, string interpolation
- Collection literals: Literal syntax for arrays, lists, sets, maps
- Special literals: Boolean values, symbols, functions, regular expressions
Mastering the use of literals is the foundation for writing clear and concise Scala code. In the next chapter, we will learn Scala Escape Characters, diving deeper into handling special characters in strings.