scalabeginner
Match Expressions with Guards
Use match expressions with guards, alternatives, and deep patterns for control flow.
scalaPress ⌘/Ctrl + Shift + C to copy
// 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.
scalabeginner
Pattern Matching Fundamentals
Use Scala pattern matching with guards, type patterns, tuple patterns, and nested extractors.
Best for: Control flow with pattern matching
#scala#pattern-matching
scalabeginner
Scala Hello World Application
Create a basic Scala application with main method, string interpolation, and val/var basics.
Best for: Getting started with Scala
#scala#basics
scalabeginner
Case Classes and Objects
Define immutable data with case classes: copy, equality, destructuring, and companion objects.
Best for: Domain modeling with immutable data
#scala#case-class
scalabeginner
Collections Map Filter Fold Operations
Master Scala collections: map, flatMap, filter, fold, groupBy, partition, and zip operations.
Best for: Data transformation and aggregation
#scala#collections