match एक Expression के रूप में
एक match expression किसी value को कई patterns से compare करता है और जो पहला पैटर्न फिट बैठे उसका जवाब वापस देता है, जैसे mail को सही slot में छांटना। यह switch का एक ज़्यादा powerful चचेरा भाई है।
In this page:
Syntax
val result = value match {
case pattern1 => result1
case pattern2 => result2
case _ => default_result
}
match as an Expression
Scala का match expression किसी value को patterns की एक series से compare करता है और, if की तरह, सिर्फ एक side effect करने के बजाय एक value produce करता है।
यह एक typical switch statement से ज़्यादा powerful है, type patterns, guards, और destructuring को support करता है, जिसे बाद के chapter में गहराई से कवर किया गया है। हर match में handle करने के लिए कम से कम एक case चाहिए, और जो specifically match न हो उसे handle करने के लिए आमतौर पर case _ wildcard उपयोग होता है।
Note:
case _ => default/catch-all branch की तरह काम करता है, जो switch statement के default जैसा है।उदाहरण: match as an Expression
object Main extends App {
val day = 3
val name = day match {
case 1 => "Monday"
case 2 => "Tuesday"
case 3 => "Wednesday"
case _ => "Unknown"
}
println(name)
}
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 _ =>default को छोड़ देना, जिससे unmatched value runtime परMatchErrorफेंकता है।- Java के
switchजैसाbreakया fall-through logic का उपयोग करना, जबकि हरcaseअकेला चलता है और fall-through नहीं होता। - cases को गलत क्रम में रखना, जैसे
case _को पहले रखना, जिससे यह सब कुछ पकड़ लेता है और बाद के cases तक कभी नहीं पहुंचता।
चैप्टर सारांश
- Arithmetic, comparison, logical, और bitwise operators values के साथ काम करते हैं।
- String concatenation text को जोड़ता है।
ifऔरmatchexpressions हैं जो values produce करते हैं।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: