Skip to content

Scala Escape Characters

Escape characters are a way to represent special characters in strings and character literals. This chapter will detail the usage of various escape characters in Scala.

Overview of Escape Characters

Escape characters start with a backslash \ and are used to represent characters that cannot be directly entered or have special meaning.

Basic Escape Characters

scala
// Common escape characters
val tab = '\t'          // Tab
val newline = '\n'      // Line Feed
val carriageReturn = '\r' // Carriage Return
val backspace = '\b'    // Backspace
val formFeed = '\f'     // Form Feed
val singleQuote = '\''  // Single quote
val doubleQuote = '\"'  // Double quote
val backslash = '\\'    // Backslash

// Using in strings
val message = "Hello\tWorld\nThis is a new line"
val path = "C:\\Users\\username\\Documents"
val quote = "He said \"Hello\" to me"

Character Escape Characters

Printable Character Escapes

scala
// Single quote needs to be escaped in character literals
val singleQuoteChar = '\''

// Double quote needs to be escaped in character literals
val doubleQuoteChar = '\"'

// Backslash needs to be escaped
val backslashChar = '\\'

// Examples
println(singleQuoteChar)  // '
println(doubleQuoteChar)  // "
println(backslashChar)    // \

Control Character Escapes

scala
// Tab
val tab = '\t'
println(s"Name${tab}Age${tab}City")
// Output: Name    Age    City

// Newline
val newline = '\n'
println(s"First Line${newline}Second Line")
// Output:
// First Line
// Second Line

// Carriage return (usually used with newline)
val crlf = "\r\n"  // Windows-style line ending

// Backspace
val backspace = '\b'
println(s"Hello${backspace} World")  // Delete one character

// Form feed
val formFeed = '\f'
println(s"Page 1${formFeed}Page 2")  // Page break

String Escape Characters

Using Escapes in Normal Strings

scala
// Strings containing escape characters
val text1 = "Line 1\nLine 2\nLine 3"
val text2 = "Column1\tColumn2\tColumn3"
val text3 = "She said \"Hello\" to him"
val text4 = "File path: C:\\Program Files\\MyApp"

println(text1)
// Output:
// Line 1
// Line 2
// Line 3

println(text2)
// Output: Column1    Column2    Column3

println(text3)
// Output: She said "Hello" to him

println(text4)
// Output: File path: C:\Program Files\MyApp

Escape Character Combinations

scala
// Multiple escape characters used together
val formatted = "Name:\t\"John Doe\"\nAge:\t25\nCity:\t\"New York\""
println(formatted)
// Output:
// Name:    "John Doe"
// Age:     25
// City:    "New York"

// Table format
val table = "ID\tName\t\tSalary\n" +
           "1\tAlice\t\t$50,000\n" +
           "2\tBob\t\t$60,000\n" +
           "3\tCharlie\t$55,000"
println(table)

Unicode Escape Characters

Basic Unicode Escapes

scala
// Unicode escape format: \uXXXX (4-digit hexadecimal)
val unicodeA = '\u0041'      // 'A'
val unicodeHeart = '\u2764'  // ❤
val unicodeSmiley = '\u263A' // ☺
val unicodeChinese = '\u4E2D' // 中

println(s"Unicode A: $unicodeA")
println(s"Heart: $unicodeHeart")
println(s"Smiley: $unicodeSmiley")
println(s"Chinese: $unicodeChinese")

// Using Unicode in strings
val greeting = "Hello \u4E16\u754C"  // Hello 世界
println(greeting)

Common Unicode Characters

scala
// Mathematical symbols
val pi = '\u03C0'           // π
val infinity = '\u221E'     // ∞
val sum = '\u2211'          // ∑
val integral = '\u222B'     // ∫

// Currency symbols
val dollar = '\u0024'       // $
val euro = '\u20AC'         // €
val yen = '\u00A5'          // ¥
val pound = '\u00A3'        // £

// Arrow symbols
val leftArrow = '\u2190'    // ←
val rightArrow = '\u2192'   // →
val upArrow = '\u2191'      // ↑
val downArrow = '\u2193'    // ↓

// Create a string with various symbols
val symbols = s"Math: $pi $infinity $sum | Currency: $dollar $euro $yen | Arrows: $leftArrow $rightArrow"
println(symbols)

Chinese Character Unicode

scala
// Unicode of common Chinese characters
val chinese = Map(
  "你" -> '\u4F60',
  "好" -> '\u597D',
  "世" -> '\u4E16',
  "界" -> '\u754C',
  "中" -> '\u4E2D',
  "国" -> '\u56FD'
)

// Use Unicode to build Chinese strings
val hello = s"${chinese("你")}${chinese("好")}"
val world = s"${chinese("世")}${chinese("界")}"
val china = s"${chinese("中")}${chinese("国")}"

println(s"$hello $world")  // 你好 世界
println(china)             // 中国

Octal Escape Characters

Octal Escape Format

scala
// Octal escape format: \nnn (1-3 digit octal number)
val octalA = '\101'         // 'A' (octal 101 = decimal 65)
val octalNewline = '\012'   // '\n' (octal 12 = decimal 10)
val octalTab = '\011'       // '\t' (octal 11 = decimal 9)
val octalNull = '\0'        // null character (octal 0 = decimal 0)

println(s"Octal A: $octalA")
println(s"Octal newline creates new line:$octalNewline")
println(s"Octal${octalTab}tab")

// Octal digit ranges
val octal1 = '\1'           // 1 digit octal
val octal12 = '\12'         // 2 digit octal
val octal123 = '\123'       // 3 digit octal (decimal 83, character 'S')

println(s"Octal 123 represents: $octal123")

Escaping in Raw Strings

Raw String Characteristics

scala
// Raw strings (triple quotes) don't need escaping
val rawString = """This is a raw string.
It can contain "quotes" and \backslashes
without escaping them.
Even \n and \t are literal characters."""

println(rawString)

// Compare with normal strings
val normalString = "This needs escaping: \"quotes\" and \\backslashes\nNew line here"
println(normalString)

// Application in regular expressions
val emailRegex = """[\w\.-]+@[\w\.-]+\.\w+"""  // No need for double escaping
val pathRegex = """C:\\Users\\[^\\]+\\Documents"""  // Still need to escape backslashes

// Compare with regular expression in normal strings
val emailRegexNormal = "[\\w\\.-]+@[\\w\\.-]+\\.\\w+"  // Need double escaping

Escaping in String Interpolation

Escaping in s Interpolator

scala
val name = "Alice"
val age = 25

// Using escape characters in s interpolator
val message1 = s"Name:\t$name\nAge:\t$age"
println(message1)

// Escape special characters in interpolation expressions
val price = 19.99
val currency = "$"
val formatted = s"Price: \\$price $currency"  // Escape $ symbol
println(formatted)  // Price: $price $

// Correct way
val correctFormatted = s"Price: $currency$price"
println(correctFormatted)  // Price: $19.99

Escaping in f Interpolator

scala
val pi = math.Pi
val percentage = 0.856

// Escaping in f interpolator
val formatted1 = f"Pi: $pi%.2f\nPercentage: ${percentage * 100}%.1f%%"
println(formatted1)
// Output:
// Pi: 3.14
// Percentage: 85.6%

// Escape percent sign
val progress = 75
val progressMsg = f"Progress: $progress%%"  // %% represents literal %
println(progressMsg)  // Progress: 75%

Escaping in raw Interpolator

scala
val path = "Documents"
val user = "Alice"

// raw interpolator does not process escape characters
val rawPath = raw"C:\Users\$user\$path"
println(rawPath)  // C:\Users\Alice\Documents

// Compare with s interpolator
val sPath = s"C:\\Users\\$user\\$path"
println(sPath)    // C:\Users\Alice\Documents

// Newlines in raw interpolator
val rawMultiline = raw"Line 1\nLine 2\tTabbed"
println(rawMultiline)  // Line 1\nLine 2\tTabbed (literal)

val sMultiline = s"Line 1\nLine 2\tTabbed"
println(sMultiline)
// Output:
// Line 1
// Line 2    Tabbed

Practical Application Examples

Log Formatting

scala
object Logger {
  def formatLogEntry(level: String, component: String, message: String): String = {
    val timestamp = java.time.LocalDateTime.now()
    s"[$timestamp]\t$level\t$component:\t$message"
  }

  def info(component: String, message: String): Unit = {
    println(formatLogEntry("INFO", component, message))
  }

  def error(component: String, message: String): Unit = {
    println(formatLogEntry("ERROR", component, message))
  }

  def debug(component: String, message: String): Unit = {
    println(formatLogEntry("DEBUG", component, message))
  }
}

// Usage example
Logger.info("Database", "Connection established")
Logger.error("API", "Request failed with status 500")
Logger.debug("Cache", "Cache hit for key \"user:123\"")

CSV Data Processing

scala
object CSVProcessor {
  def createCSVRow(fields: String*): String = {
    fields.map { field =>
      if (field.contains(",") || field.contains("\"") || field.contains("\n")) {
        // Fields containing special characters need to be surrounded by quotes, internal quotes need escaping
        "\"" + field.replace("\"", "\"\"") + "\""
      } else {
        field
      }
    }.mkString(",")
  }

  def parseCSVRow(row: String): List[String] = {
    // Simplified CSV parsing (in practice, use specialized libraries)
    row.split(",").map(_.trim.stripPrefix("\"").stripSuffix("\"")).toList
  }
}

// Usage example
val csvData = List(
  CSVProcessor.createCSVRow("John Doe", "30", "Engineer", "\"Hello, World!\""),
  CSVProcessor.createCSVRow("Jane Smith", "25", "Designer", "Creative\nThinker"),
  CSVProcessor.createCSVRow("Bob Johnson", "35", "Manager", "Team Leader")
)

csvData.foreach(println)
// Output:
// John Doe,30,Engineer,"""Hello, World!"""
// Jane Smith,25,Designer,"Creative
// Thinker"
// Bob Johnson,35,Manager,Team Leader

Configuration File Generation

scala
object ConfigGenerator {
  def generateProperties(config: Map[String, String]): String = {
    val header = "# Application Configuration\n# Generated on " +
                java.time.LocalDateTime.now() + "\n\n"

    val properties = config.map { case (key, value) =>
      // Escape special characters in property values
      val escapedValue = value
        .replace("\\", "\\\\")  // Backslash
        .replace("\n", "\\n")   // Newline
        .replace("\r", "\\r")   // Carriage return
        .replace("\t", "\\t")   // Tab
        .replace("=", "\\=")    // Equals sign
        .replace(":", "\\:")    // Colon

      s"$key=$escapedValue"
    }.mkString("\n")

    header + properties
  }
}

// Usage example
val appConfig = Map(
  "app.name" -> "My Scala App",
  "app.version" -> "1.0.0",
  "database.url" -> "jdbc:postgresql://localhost:5432/mydb",
  "log.pattern" -> "%d{yyyy-MM-dd HH:mm:ss} [%level] %logger{36} - %msg%n",
  "file.path" -> "C:\\Program Files\\MyApp\\data"
)

val propertiesContent = ConfigGenerator.generateProperties(appConfig)
println(propertiesContent)

JSON String Processing

scala
object JSONEscaper {
  def escapeJSONString(str: String): String = {
    str
      .replace("\\", "\\\\")  // Backslash
      .replace("\"", "\\\"")  // Double quote
      .replace("\b", "\\b")   // Backspace
      .replace("\f", "\\f")   // Form feed
      .replace("\n", "\\n")   // Newline
      .replace("\r", "\\r")   // Carriage return
      .replace("\t", "\\t")   // Tab
  }

  def createJSONString(key: String, value: String): String = {
    s""""${escapeJSONString(key)}": "${escapeJSONString(value)}""""
  }

  def createJSONObject(fields: Map[String, String]): String = {
    val jsonFields = fields.map { case (key, value) =>
      createJSONString(key, value)
    }.mkString(",\n  ")

    s"{\n  $jsonFields\n}"
  }
}

// Usage example
val userData = Map(
  "name" -> "John \"Johnny\" Doe",
  "bio" -> "Software engineer\nLoves coding\tand coffee",
  "website" -> "https://johndoe.com/path?param=value",
  "notes" -> "Special chars: \\ / \" \n \t"
)

val jsonString = JSONEscaper.createJSONObject(userData)
println(jsonString)

Exercises

Exercise 1: Escape Character Recognition

scala
object EscapeCharacterExercise {
  def analyzeString(input: String): Unit = {
    println(s"Original string: \"$input\"")
    println(s"Length: ${input.length}")

    val escapeChars = input.zipWithIndex.collect {
      case ('\t', i) => s"Tab at position $i"
      case ('\n', i) => s"Newline at position $i"
      case ('\r', i) => s"Carriage return at position $i"
      case ('\\', i) => s"Backslash at position $i"
      case ('\"', i) => s"Double quote at position $i"
    }

    if (escapeChars.nonEmpty) {
      println("Escape characters found:")
      escapeChars.foreach(println)
    } else {
      println("No escape characters found")
    }

    println(s"Displayed string:\n$input")
    println("-" * 40)
  }

  def main(args: Array[String]): Unit = {
    val testStrings = List(
      "Hello\tWorld",
      "Line 1\nLine 2",
      "Path: C:\\Users\\John",
      "He said \"Hello\"",
      "Normal string without escapes",
      "Mixed:\tTab\nNewline\\Backslash\"Quote"
    )

    testStrings.foreach(analyzeString)
  }
}

Exercise 2: Unicode Character Processing

scala
object UnicodeExercise {
  // Unicode range definitions
  val unicodeRanges = Map(
    "Basic Latin" -> (0x0000 to 0x007F),
    "CJK Unified Ideographs" -> (0x4E00 to 0x9FFF),
    "Mathematical Operators" -> (0x2200 to 0x22FF),
    "Currency Symbols" -> (0x20A0 to 0x20CF),
    "Arrows" -> (0x2190 to 0x21FF)
  )

  def analyzeUnicodeString(str: String): Unit = {
    println(s"Analyzing: \"$str\"")

    str.foreach { char =>
      val codePoint = char.toInt
      val unicodeName = unicodeRanges.find { case (_, range) =>
        range.contains(codePoint)
      }.map(_._1).getOrElse("Other")

      println(f"'$char' -> U+$codePoint%04X ($unicodeName)")
    }
    println()
  }

  def createUnicodeDemo(): String = {
    val mathSymbols = "\u03C0\u221E\u2211\u222B"  // π∞∑∫
    val currencies = "\u0024\u20AC\u00A5\u00A3"   // $€¥£
    val arrows = "\u2190\u2192\u2191\u2193"       // ←→↑↓
    val chinese = "\u4F60\u597D\u4E16\u754C"     // 你好世界

    s"Math: $mathSymbols | Money: $currencies | Arrows: $arrows | Chinese: $chinese"
  }

  def main(args: Array[String]): Unit = {
    val demo = createUnicodeDemo()
    analyzeUnicodeString(demo)

    // Test other strings
    analyzeUnicodeString("Hello 世界!")
    analyzeUnicodeString("Price: $19.99 €15.50")
  }
}

Summary

This chapter detailed the usage of escape characters in Scala:

  • Basic Escape Characters: \t, \n, \r, \\, \", \', etc.
  • Unicode Escapes: \uXXXX format for Unicode characters
  • Octal Escapes: \nnn format for octal characters
  • Escaping in Strings: Normal strings vs raw strings
  • Escaping in String Interpolation: Different behaviors of s, f, raw interpolators
  • Practical Applications: Log formatting, CSV processing, JSON generation, etc.

Mastering the use of escape characters is very important for processing text data, formatted output, and string operations. In the next chapter, we will learn about Scala Access Modifiers, understanding how to control access to classes and members.

Content is for learning and research only.