You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Once you have a populated list, the following examples show some of the methods you can call on it.
39
38
Notice that these are all functional methods, meaning that they don’t mutate the collection they’re called on, but instead return a new collection with the updated elements.
40
39
The result that’s returned by each expression is shown in the comment on each line:
firstTen.foldLeft(100)(_ + _) // 155 (100 is a “seed” value)
71
76
```
77
+
{% endtab %}
78
+
{% endtabs %}
72
79
73
80
There are many more methods available to Scala collections classes, and they’re demonstrated in the [Collections chapter][collections], and in the [API Documentation][api].
74
81
75
-
76
-
77
82
## Tuples
78
83
79
84
The Scala _tuple_ is a type that lets you easily put a collection of different types in the same container.
80
85
For example, given this `Person` case class:
81
86
87
+
{% tabs collection_4 class=tabs-scala-version %}
88
+
{% tab 'Scala 2 and 3' for=collection_4 %}
82
89
```scala
83
90
caseclassPerson(name: String)
84
91
```
92
+
{% endtab %}
93
+
{% endtabs %}
85
94
86
95
This is how you create a tuple that contains an `Int`, a `String`, and a custom `Person` value:
87
96
97
+
{% tabs collection_5 class=tabs-scala-version %}
98
+
{% tab 'Scala 2 and 3' for=collection_5 %}
88
99
```scala
89
100
valt= (11, "eleven", Person("Eleven"))
90
101
```
102
+
{% endtab %}
103
+
{% endtabs %}
91
104
92
105
Once you have a tuple, you can access its values by binding them to variables, or access them by number:
93
106
107
+
{% tabs collection_6 class=tabs-scala-version %}
108
+
{% tab 'Scala 2 and 3' for=collection_6 %}
94
109
```scala
95
110
t(0) // 11
96
111
t(1) // "eleven"
97
112
t(2) // Person("Eleven")
98
113
```
114
+
{% endtab %}
115
+
{% endtabs %}
99
116
100
117
You can also use this _extractor_ approach to assign the tuple fields to variable names:
101
118
119
+
{% tabs collection_7 class=tabs-scala-version %}
120
+
{% tab 'Scala 2 and 3' for=collection_7 %}
102
121
```scala
103
122
val (num, str, person) = t
104
123
@@ -107,13 +126,12 @@ val (num, str, person) = t
107
126
// val str: String = eleven
108
127
// val person: Person = Person(Eleven)
109
128
```
129
+
{% endtab %}
130
+
{% endtabs %}
110
131
111
132
Tuples are nice for those times when you want to put a collection of heterogeneous types in a little collection-like structure.
112
133
See the [Reference documentation][reference] for more tuple details.
113
134
114
-
115
-
116
-
117
135
[collections]: {% link _overviews/scala3-book/collections-intro.md %}
0 commit comments