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

Basic match क्या है

एक basic match किसी value को patterns की एक list से compare करता है और जो पहला फिट बैठे उसे चलाता है, जैसे एक sorting hat हर item को उसके house में रखता है। यह if की लंबी chains की जगह लेता है।

In this page:

  1. Basic match
Syntax
scala
value match {
  case pattern1 => result1
  case pattern2 => result2
  case _        => default_result
}

Basic match

एक match expression किसी value को case patterns की एक series से compare करता है, पहले मेल खाने वाले को चलाता है (और उसकी value produce करता है)।

case _ => एक catch-all default की तरह काम करता है, और कुछ sealed types के लिए अगर match exhaustive न हो तो Scala चेतावनी देता है (या settings के आधार पर error देता है)। चूंकि match एक expression है, इसलिए इसका result सीधे किसी val को assign किया जा सकता है।

Note: Patterns को ऊपर से नीचे जांचा जाता है, और सिर्फ पहला match करने वाला case चलता है -- जब patterns overlap हो सकते हों तो order मायने रखता है।

उदाहरण: Basic match

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 _ छोड़ देना, जिससे किसी भी चीज़ से मेल न खाने वाली value MatchError फेंकती है।
  2. यह उम्मीद करना कि match Java के switch की तरह fall through करेगा, जबकि सिर्फ पहला मेल खाने वाला case चलता है।
  3. comparison के साथ case day == 3 => लिखना, जबकि कोई case एक pattern लेता है, और conditions को if के साथ guard चाहिए।
🔒

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.