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

Case Classes का Matching

Case classes पर matching किसी object के अंदर झांकता है और उसकी kind जांचते समय उसकी fields निकाल लेता है। यह toy box खोलकर हर item पर लगे labels पढ़ने जैसा है।

In this page:

  1. Matching Case Classes
Syntax
scala
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

markup
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)
}
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. case class के बजाय plain class का उपयोग करना और case Point(x, y) के काम करने की उम्मीद करना, जबकि plain class में कोई unapply नहीं होता।
  2. pattern में galat संख्या में fields लिखना, जैसे दो-field class के लिए case Point(x)।
  3. यह मान लेना कि pattern variables var हैं, जबकि वे सिर्फ उस case के लिए नए val bindings हैं।
🔒

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.