Tuples का Matching
Tuples पर matching एक बंडल खोलता है और उसके हिस्सों को एक ही बार में नाम देता है, जैसे lunch tray को sandwich और juice में खोलना। फिर आप हर हिस्से पर काम कर सकते हैं।
In this page:
Syntax
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
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)
}
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. #}
आम गलतियां
- किसी tuple को गलत size के pattern के खिलाफ match करना, जैसे 2-tuple पर
case (a, b, c), जो compile नहीं होता। - किसी pattern में capital letter से शुरू होने वाले variable name का उपयोग करना, जैसे
case (X, 0), जहां ScalaXको compare करने के लिए एक constant मानता है। - यह भूल जाना कि
case (x, 0)सिर्फ तभी match करता है जब दूसरा element0के बराबर हो।
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: