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

Tuples का Matching

Tuples पर matching एक बंडल खोलता है और उसके हिस्सों को एक ही बार में नाम देता है, जैसे lunch tray को sandwich और juice में खोलना। फिर आप हर हिस्से पर काम कर सकते हैं।

In this page:

  1. Matching Tuples
Syntax
scala
tuple match {
  case (a, b) => expression
}

Matching Tuples

case (a, b) => जैसा एक pattern match branch के अंदर सीधे किसी tuple को उसके component parts में destructure करता है, हर part को एक नए variable से जोड़ता है।

यह किसी भी size के tuples के लिए काम करता है और individual components पर type या literal patterns के साथ combine किया जा सकता है। यह बार-बार ._1, ._2 call करने की तुलना में tuple contents के साथ काम करने का कहीं ज़्यादा सीधा तरीका है।

Note: Tuple patterns literal values और variable bindings मिला सकते हैं, जैसे case (0, y) => ... सिर्फ तभी match करने के लिए जब पहला element बिल्कुल 0 हो।

उदाहरण: Matching Tuples

markup
object Main extends App {
  val point = (3, 4)

  val description = point match {
    case (0, 0) => "origin"
    case (x, 0) => s"on the x-axis at $x"
    case (0, y) => s"on the y-axis at $y"
    case (x, y) => s"at ($x, $y)"
  }

  println(description)
}
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. किसी tuple को गलत size के pattern के खिलाफ match करना, जैसे 2-tuple पर case (a, b, c), जो compile नहीं होता।
  2. किसी pattern में capital letter से शुरू होने वाले variable name का उपयोग करना, जैसे case (X, 0), जहां Scala X को compare करने के लिए एक constant मानता है।
  3. यह भूल जाना कि case (x, 0) सिर्फ तभी match करता है जब दूसरा element 0 के बराबर हो।
🔒

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.