scalabeginner

Match Expressions with Guards

Use match expressions with guards, alternatives, and deep patterns for control flow.

scala
// FizzBuzz with match
def fizzBuzz(n: Int): String = (n % 3, n % 5) match
  case (0, 0) => "FizzBuzz"
  case (0, _) => "Fizz"
  case (_, 0) => "Buzz"
  case _      => n.toString

// HTTP response handler
def handleResponse(code: Int, body: String): String = code match
  case 200 | 201 | 204              => s"Success: $body"
  case c if c >= 300 && c < 400     => s"Redirect ($c)"
  case 401 | 403                    => s"Auth error ($code)"
  case 404                          => "Not found"
  case 429                          => "Rate limited"
  case c if c >= 500                => s"Server error ($c): $body"
  case _                            => s"Unknown ($code)"

// Grading system
def grade(score: Int): String = score match
  case s if s >= 90 => "A"
  case s if s >= 80 => "B"
  case s if s >= 70 => "C"
  case s if s >= 60 => "D"
  case _            => "F"

// Command parser
def parseCommand(input: String): String =
  input.trim.toLowerCase.split("\\s+").toList match
    case "quit" :: Nil              => "Quitting"
    case "help" :: Nil              => "Available: quit, help, add, list"
    case "add" :: item :: Nil       => s"Adding: $item"
    case "add" :: items             => s"Adding: ${items.mkString(", ")}"
    case "list" :: Nil              => "Listing all items"
    case "search" :: query :: _     => s"Searching for: $query"
    case cmd :: _                   => s"Unknown command: $cmd"
    case Nil                        => "Empty input"

// Nested match
case class Config(debug: Boolean, logLevel: String, port: Option[Int])

def describeConfig(config: Config): String = config match
  case Config(true, level, Some(port)) =>
    s"Debug mode on $level at port $port"
  case Config(true, level, None) =>
    s"Debug mode on $level (default port)"
  case Config(false, "error", _) =>
    "Production (errors only)"
  case Config(false, _, Some(port)) if port > 1024 =>
    s"Production on port $port"
  case _ =>
    "Default config"

@main def run(): Unit =
  // FizzBuzz
  println((1 to 20).map(fizzBuzz).mkString(", "))
  println()

  // HTTP responses
  println(handleResponse(200, "OK"))
  println(handleResponse(301, ""))
  println(handleResponse(404, ""))
  println(handleResponse(500, "Internal error"))
  println()

  // Grades
  List(95, 85, 75, 65, 55).foreach { s =>
    println(s"$s -> ${grade(s)}")
  }
  println()

  // Commands
  List("add item1", "add x y z", "search foo", "quit", "help", "unknown")
    .foreach(cmd => println(s"  '$cmd' -> ${parseCommand(cmd)}"))
  println()

  // Config
  println(describeConfig(Config(true, "debug", Some(8080))))
  println(describeConfig(Config(false, "error", None)))
  println(describeConfig(Config(false, "info", Some(9090))))

Use Cases

  • Control flow with pattern matching
  • Command parsing
  • Response handling

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.