← Back to Scala Course | Chapter 3: Operators & Expressions | Lesson 7 of 7

match एक Expression के रूप में

एक match expression किसी value को कई patterns से compare करता है और जो पहला पैटर्न फिट बैठे उसका जवाब वापस देता है, जैसे mail को सही slot में छांटना। यह switch का एक ज़्यादा powerful चचेरा भाई है।

In this page:

  1. match as an Expression
Syntax
scala
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

markup
object Main extends App {
  val day = 3

  val name = day match {
    case 1 => "Monday"
    case 2 => "Tuesday"
    case 3 => "Wednesday"
    case _ => "Unknown"
  }

  println(name)
}
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 _ => default को छोड़ देना, जिससे unmatched value runtime पर MatchError फेंकता है।
  2. Java के switch जैसा break या fall-through logic का उपयोग करना, जबकि हर case अकेला चलता है और fall-through नहीं होता।
  3. cases को गलत क्रम में रखना, जैसे case _ को पहले रखना, जिससे यह सब कुछ पकड़ लेता है और बाद के cases तक कभी नहीं पहुंचता।
चैप्टर सारांश
  • Arithmetic, comparison, logical, और bitwise operators values के साथ काम करते हैं।
  • String concatenation text को जोड़ता है।
  • if और match expressions हैं जो values produce करते हैं।
🔒

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.