← Back to Scala Course | Chapter 6: Collections Basics | Lesson 7 of 8

Tuples क्या हैं

एक tuple कुछ values को एक साथ बांध देता है, भले ही अलग-अलग kinds की हों, जैसे sandwich, apple, और juice वाली lunch tray। यह कई facts को एक के रूप में ले जाने का तेज़ तरीका है।

In this page:

  1. Tuples
Syntax
scala
val tuple = (value1, value2, value3)
tuple._1
val (a, b, c) = tuple

Tuples

एक tuple शायद अलग-अलग types की values की एक निश्चित संख्या को एक साथ group करता है, जिसे (1, "two", 3.0) लिखा जाता है, जिसका type (Int, String, Double) जैसा होता है।

Elements को ._1, ._2, आदि से access किया जाता है (1-indexed, ज़्यादातर Scala collections के विपरीत)। किसी dedicated case class को define किए बिना function से कई values return करने के लिए Tuples सुविधाजनक हैं।

Note: ._1, ._2 से tuple field access 1-indexed है, array/list indexing के विपरीत जो 0 से शुरू होती है।

उदाहरण: Tuples

markup
object Main extends App {
  val person = ("Alice", 30, true)

  println(person._1)
  println(person._2)
  println(person._3)

  val (name, age, active) = person
  println(s"$name is $age, active: $active")
}
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 को zero से index करना, जैसे person._0, जबकि tuple positions _1 से शुरू होती हैं।
  2. person._1 = "Bob" जैसे किसी tuple value को बदलने की कोशिश करना, जबकि tuples immutable हैं।
  3. गलत संख्या में variables के साथ destructure करना, जैसे 3-tuple पर val (a, b) = person, जिससे compile error आता है।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 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.