← Back to Scala Course | Chapter 10: Pattern Matching | Lesson 6 of 7

नेस्टेड Patterns

Nested patterns उन चीज़ों के अंदर देखते हैं जो दूसरी चीज़ों के अंदर होती हैं, जैसे किसी box के अंदर box जांचना। आप एक साफ़ line में कोई गहरी detail match कर सकते हैं।

In this page:

  1. Nested Patterns
Syntax
scala
value match {
  case Some(ClassName(a, b)) => expression
  case _                     => default_result
}

Nested Patterns

Patterns एक-दूसरे के अंदर nest हो सकते हैं, जैसे case Some(Point(0, 0)) =>, एक ही case में किसी structure के shape में गहराई से match करते हुए।

यह एक single pattern को वे conditions express करने देता है जिन्हें अन्यथा कई अलग nested if/match statements चाहिए होंगे। Nested patterns case classes और Option तथा List जैसे standard types के साथ मिलकर खासतौर पर शक्तिशाली हैं।

Note: Nested patterns आपको एक ही case में मनचाही गहराई तक structure match करने देते हैं, जिससे nested match/if statements का एक pyramid बनने से बचा जाता है।

उदाहरण: Nested Patterns

markup
case class Point(x: Int, y: Int)
case class Line(start: Point, end: Point)

object Main extends App {
  val line = Line(Point(0, 0), Point(5, 5))

  val description = line match {
    case Line(Point(0, 0), Point(x, y)) => s"starts at origin, ends at ($x, $y)"
    case Line(a, b) => s"from $a to $b"
  }

  println(description)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी Option[Line] पर case Some(Point(0, 0)) लिखना, जिसका nested type गलत है।
  2. patterns को इतना गहराई से nest करना कि code अपठनीय हो जाए, जबकि @ के साथ एक helper variable मदद कर सकता है।
  3. None case भूल जाना, जिससे match non-exhaustive हो जाता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.