नेस्टेड Patterns
Nested patterns उन चीज़ों के अंदर देखते हैं जो दूसरी चीज़ों के अंदर होती हैं, जैसे किसी box के अंदर box जांचना। आप एक साफ़ line में कोई गहरी detail match कर सकते हैं।
In this page:
Syntax
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- किसी
Option[Line]परcase Some(Point(0, 0))लिखना, जिसका nested type गलत है। - patterns को इतना गहराई से nest करना कि code अपठनीय हो जाए, जबकि
@के साथ एक helper variable मदद कर सकता है। Nonecase भूल जाना, जिससे match non-exhaustive हो जाता है।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: