Case Classes का Matching
Case classes पर matching किसी object के अंदर झांकता है और उसकी kind जांचते समय उसकी fields निकाल लेता है। यह toy box खोलकर हर item पर लगे labels पढ़ने जैसा है।
In this page:
Syntax
value match {
case ClassName(field1, field2) => expression
case OtherClass(field) => expression
}
Matching Case Classes
Case classes सीधे अपनी fields पर pattern matching को support करते हैं, जैसे case Point(x, y) =>, branch के अंदर ._1-style accessors को call किए बिना किसी instance को उसके constructor parameters में destructure करते हुए।
यह इसलिए काम करता है क्योंकि case classes अपने आप एक unapply method generate करते हैं जिस पर pattern matching पीछे से निर्भर करता है। यही एक बड़ी वजह है कि idiomatic Scala में data modeling के लिए case classes को प्राथमिकता दी जाती है।
Note:
Case classes पर pattern matching अपने आप generate हुए unapply method पर निर्भर करता है -- यही वजह है कि case classes इसे support करते हैं और plain classes default रूप से नहीं।
उदाहरण: Matching Case Classes
case class Point(x: Int, y: Int)
object Main extends App {
val p = Point(3, 4)
val description = p match {
case Point(0, 0) => "origin"
case Point(x, y) => s"at ($x, $y)"
}
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. #}
आम गलतियां
case classके बजाय plain class का उपयोग करना औरcase Point(x, y)के काम करने की उम्मीद करना, जबकि plain class में कोईunapplyनहीं होता।- pattern में galat संख्या में fields लिखना, जैसे दो-field class के लिए
case Point(x)। - यह मान लेना कि pattern variables
varहैं, जबकि वे सिर्फ उस case के लिए नएvalbindings हैं।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: