Types का Matching
Types पर matching यह जांचता है कि कोई value किस तरह की है और तदनुसार react करता है, जैसे एक mail sorter यह देखता है कि वह letter है या parcel। हर case एक type नाम देता है।
In this page:
Syntax
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
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))
}
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 l: List[Int] =>जैसे generic types पर match करना, जो unchecked है क्योंकि type arguments runtime पर erase हो जाते हैं।- type pattern के बजाय
isInstanceOfऔरasInstanceOfसे cast करना, जो लंबा और कम सुरक्षित है। - ज़्यादा specific types से पहले
case _: Anyरखना, जिससे specific cases तक कभी नहीं पहुंचा जाता।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: