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

Types का Matching

Types पर matching यह जांचता है कि कोई value किस तरह की है और तदनुसार react करता है, जैसे एक mail sorter यह देखता है कि वह letter है या parcel। हर case एक type नाम देता है।

In this page:

  1. Matching Types
Syntax
scala
value match {
  case x: Int    => expression
  case s: String => expression
  case _         => default_result
}

Matching Types

एक case variableName: Type => pattern किसी value के runtime type के आधार पर match करता है, और branch के अंदर इसे उस specific type के एक नए variable से जोड़ देता है।

यह manual isInstanceOf/asInstanceOf type checks और casts का Scala का संरचित विकल्प है। यह तब खासतौर पर उपयोगी है जब किसी value का static type एक broad supertype हो लेकिन आपको कई संभावित concrete subtypes को अलग-अलग तरीके से handle करना हो।

Note: case s: String => ... type जांचता भी है और branch के अंदर उपयोग के लिए एक सही-typed variable s भी देता है।

उदाहरण: Matching Types

markup
object Main extends App {
  def describe(x: Any): String = x match {
    case i: Int => s"An Int: $i"
    case s: String => s"A String of length ${s.length}"
    case _ => "Something else"
  }

  println(describe(42))
  println(describe("hello"))
  println(describe(3.14))
}
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 l: List[Int] => जैसे generic types पर match करना, जो unchecked है क्योंकि type arguments runtime पर erase हो जाते हैं।
  2. type pattern के बजाय isInstanceOf और asInstanceOf से cast करना, जो लंबा और कम सुरक्षित है।
  3. ज़्यादा specific types से पहले case _: Any रखना, जिससे specific cases तक कभी नहीं पहुंचा जाता।
🔒

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.