Skip to content

Commit 2662c21

Browse files
flomebulbishabosha
andauthoredOct 4, 2022
Add code tabs for collections-2.13/arrays, strings, equality and views (#2574)
* Add code tabs for collections-2.13/arrays * Add code tabs for collections-2.13/strings * Add code tabs for collections-2.13/equality * Add code tabs for collections-2.13/views * Add code tabs for collections-2.13/iterators * Add code tabs for collections-2.13/views * format code examples Co-authored-by: Jamie Thompson <[email protected]>
1 parent c2c13fa commit 2662c21

File tree

4 files changed

+384
-108
lines changed

4 files changed

+384
-108
lines changed
 

‎_overviews/collections-2.13/arrays.md

Lines changed: 178 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -14,106 +14,229 @@ permalink: /overviews/collections-2.13/:title.html
1414

1515
[Array](https://www.scala-lang.org/api/{{ site.scala-version }}/scala/Array.html) is a special kind of collection in Scala. On the one hand, Scala arrays correspond one-to-one to Java arrays. That is, a Scala array `Array[Int]` is represented as a Java `int[]`, an `Array[Double]` is represented as a Java `double[]` and a `Array[String]` is represented as a Java `String[]`. But at the same time, Scala arrays offer much more than their Java analogues. First, Scala arrays can be _generic_. That is, you can have an `Array[T]`, where `T` is a type parameter or abstract type. Second, Scala arrays are compatible with Scala sequences - you can pass an `Array[T]` where a `Seq[T]` is required. Finally, Scala arrays also support all sequence operations. Here's an example of this in action:
1616

17-
scala> val a1 = Array(1, 2, 3)
18-
a1: Array[Int] = Array(1, 2, 3)
19-
scala> val a2 = a1 map (_ * 3)
20-
a2: Array[Int] = Array(3, 6, 9)
21-
scala> val a3 = a2 filter (_ % 2 != 0)
22-
a3: Array[Int] = Array(3, 9)
23-
scala> a3.reverse
24-
res0: Array[Int] = Array(9, 3)
17+
{% tabs arrays_1 %}
18+
{% tab 'Scala 2 and 3' for=arrays_1 %}
19+
```scala
20+
scala> val a1 = Array(1, 2, 3)
21+
val a1: Array[Int] = Array(1, 2, 3)
22+
23+
scala> val a2 = a1.map(_ * 3)
24+
val a2: Array[Int] = Array(3, 6, 9)
25+
26+
scala> val a3 = a2.filter(_ % 2 != 0)
27+
val a3: Array[Int] = Array(3, 9)
28+
29+
scala> a3.reverse
30+
val res0: Array[Int] = Array(9, 3)
31+
```
32+
{% endtab %}
33+
{% endtabs %}
2534

2635
Given that Scala arrays are represented just like Java arrays, how can these additional features be supported in Scala? The Scala array implementation makes systematic use of implicit conversions. In Scala, an array does not pretend to _be_ a sequence. It can't really be that because the data type representation of a native array is not a subtype of `Seq`. Instead there is an implicit "wrapping" conversion between arrays and instances of class `scala.collection.mutable.ArraySeq`, which is a subclass of `Seq`. Here you see it in action:
2736

28-
scala> val seq: collection.Seq[Int] = a1
29-
seq: scala.collection.Seq[Int] = ArraySeq(1, 2, 3)
30-
scala> val a4: Array[Int] = seq.toArray
31-
a4: Array[Int] = Array(1, 2, 3)
32-
scala> a1 eq a4
33-
res1: Boolean = false
37+
{% tabs arrays_2 %}
38+
{% tab 'Scala 2 and 3' for=arrays_2 %}
39+
```scala
40+
scala> val seq: collection.Seq[Int] = a1
41+
val seq: scala.collection.Seq[Int] = ArraySeq(1, 2, 3)
42+
43+
scala> val a4: Array[Int] = seq.toArray
44+
val a4: Array[Int] = Array(1, 2, 3)
45+
46+
scala> a1 eq a4
47+
val res1: Boolean = false
48+
```
49+
{% endtab %}
50+
{% endtabs %}
3451

3552
The interaction above demonstrates that arrays are compatible with sequences, because there's an implicit conversion from arrays to `ArraySeq`s. To go the other way, from an `ArraySeq` to an `Array`, you can use the `toArray` method defined in `Iterable`. The last REPL line above shows that wrapping and then unwrapping with `toArray` produces a copy of the original array.
3653

3754
There is yet another implicit conversion that gets applied to arrays. This conversion simply "adds" all sequence methods to arrays but does not turn the array itself into a sequence. "Adding" means that the array is wrapped in another object of type `ArrayOps` which supports all sequence methods. Typically, this `ArrayOps` object is short-lived; it will usually be inaccessible after the call to the sequence method and its storage can be recycled. Modern VMs often avoid creating this object entirely.
3855

3956
The difference between the two implicit conversions on arrays is shown in the next REPL dialogue:
4057

41-
scala> val seq: collection.Seq[Int] = a1
42-
seq: scala.collection.Seq[Int] = ArraySeq(1, 2, 3)
43-
scala> seq.reverse
44-
res2: scala.collection.Seq[Int] = ArraySeq(3, 2, 1)
45-
scala> val ops: collection.ArrayOps[Int] = a1
46-
ops: scala.collection.ArrayOps[Int] = scala.collection.ArrayOps@2d7df55
47-
scala> ops.reverse
48-
res3: Array[Int] = Array(3, 2, 1)
58+
{% tabs arrays_3 %}
59+
{% tab 'Scala 2 and 3' for=arrays_3 %}
60+
```scala
61+
scala> val seq: collection.Seq[Int] = a1
62+
val seq: scala.collection.Seq[Int] = ArraySeq(1, 2, 3)
63+
64+
scala> seq.reverse
65+
val res2: scala.collection.Seq[Int] = ArraySeq(3, 2, 1)
66+
67+
scala> val ops: collection.ArrayOps[Int] = a1
68+
val ops: scala.collection.ArrayOps[Int] = scala.collection.ArrayOps@2d7df55
69+
70+
scala> ops.reverse
71+
val res3: Array[Int] = Array(3, 2, 1)
72+
```
73+
{% endtab %}
74+
{% endtabs %}
4975

5076
You see that calling reverse on `seq`, which is an `ArraySeq`, will give again a `ArraySeq`. That's logical, because arrayseqs are `Seqs`, and calling reverse on any `Seq` will give again a `Seq`. On the other hand, calling reverse on the ops value of class `ArrayOps` will give an `Array`, not a `Seq`.
5177

5278
The `ArrayOps` example above was quite artificial, intended only to show the difference to `ArraySeq`. Normally, you'd never define a value of class `ArrayOps`. You'd just call a `Seq` method on an array:
5379

54-
scala> a1.reverse
55-
res4: Array[Int] = Array(3, 2, 1)
80+
{% tabs arrays_4 %}
81+
{% tab 'Scala 2 and 3' for=arrays_4 %}
82+
```scala
83+
scala> a1.reverse
84+
val res4: Array[Int] = Array(3, 2, 1)
85+
```
86+
{% endtab %}
87+
{% endtabs %}
5688

5789
The `ArrayOps` object gets inserted automatically by the implicit conversion. So the line above is equivalent to
5890

59-
scala> intArrayOps(a1).reverse
60-
res5: Array[Int] = Array(3, 2, 1)
91+
{% tabs arrays_5 %}
92+
{% tab 'Scala 2 and 3' for=arrays_5 %}
93+
```scala
94+
scala> intArrayOps(a1).reverse
95+
val res5: Array[Int] = Array(3, 2, 1)
96+
```
97+
{% endtab %}
98+
{% endtabs %}
6199

62100
where `intArrayOps` is the implicit conversion that was inserted previously. This raises the question of how the compiler picked `intArrayOps` over the other implicit conversion to `ArraySeq` in the line above. After all, both conversions map an array to a type that supports a reverse method, which is what the input specified. The answer to that question is that the two implicit conversions are prioritized. The `ArrayOps` conversion has a higher priority than the `ArraySeq` conversion. The first is defined in the `Predef` object whereas the second is defined in a class `scala.LowPriorityImplicits`, which is inherited by `Predef`. Implicits in subclasses and subobjects take precedence over implicits in base classes. So if both conversions are applicable, the one in `Predef` is chosen. A very similar scheme works for strings.
63101

64102
So now you know how arrays can be compatible with sequences and how they can support all sequence operations. What about genericity? In Java, you cannot write a `T[]` where `T` is a type parameter. How then is Scala's `Array[T]` represented? In fact a generic array like `Array[T]` could be at run-time any of Java's eight primitive array types `byte[]`, `short[]`, `char[]`, `int[]`, `long[]`, `float[]`, `double[]`, `boolean[]`, or it could be an array of objects. The only common run-time type encompassing all of these types is `AnyRef` (or, equivalently `java.lang.Object`), so that's the type to which the Scala compiler maps `Array[T]`. At run-time, when an element of an array of type `Array[T]` is accessed or updated there is a sequence of type tests that determine the actual array type, followed by the correct array operation on the Java array. These type tests slow down array operations somewhat. You can expect accesses to generic arrays to be three to four times slower than accesses to primitive or object arrays. This means that if you need maximal performance, you should prefer concrete to generic arrays. Representing the generic array type is not enough, however, there must also be a way to create generic arrays. This is an even harder problem, which requires a little of help from you. To illustrate the issue, consider the following attempt to write a generic method that creates an array.
65103

66-
// this is wrong!
67-
def evenElems[T](xs: Vector[T]): Array[T] = {
68-
val arr = new Array[T]((xs.length + 1) / 2)
69-
for (i <- 0 until xs.length by 2)
70-
arr(i / 2) = xs(i)
71-
arr
72-
}
104+
{% tabs arrays_6 class=tabs-scala-version %}
105+
{% tab 'Scala 2' for=arrays_6 %}
106+
```scala mdoc:fail
107+
// this is wrong!
108+
def evenElems[T](xs: Vector[T]): Array[T] = {
109+
val arr = new Array[T]((xs.length + 1) / 2)
110+
for (i <- 0 until xs.length by 2)
111+
arr(i / 2) = xs(i)
112+
arr
113+
}
114+
```
115+
{% endtab %}
116+
{% tab 'Scala 3' for=arrays_6 %}
117+
```scala
118+
// this is wrong!
119+
def evenElems[T](xs: Vector[T]): Array[T] =
120+
val arr = new Array[T]((xs.length + 1) / 2)
121+
for i <- 0 until xs.length by 2 do
122+
arr(i / 2) = xs(i)
123+
arr
124+
```
125+
{% endtab %}
126+
{% endtabs %}
73127

74128
The `evenElems` method returns a new array that consist of all elements of the argument vector `xs` which are at even positions in the vector. The first line of the body of `evenElems` creates the result array, which has the same element type as the argument. So depending on the actual type parameter for `T`, this could be an `Array[Int]`, or an `Array[Boolean]`, or an array of some other primitive types in Java, or an array of some reference type. But these types have all different runtime representations, so how is the Scala runtime going to pick the correct one? In fact, it can't do that based on the information it is given, because the actual type that corresponds to the type parameter `T` is erased at runtime. That's why you will get the following error message if you compile the code above:
75129

76-
error: cannot find class manifest for element type T
77-
val arr = new Array[T]((arr.length + 1) / 2)
78-
^
130+
{% tabs arrays_7 class=tabs-scala-version %}
131+
{% tab 'Scala 2' for=arrays_7 %}
132+
```scala
133+
error: cannot find class manifest for element type T
134+
val arr = new Array[T]((arr.length + 1) / 2)
135+
^
136+
```
137+
{% endtab %}
138+
{% tab 'Scala 3' for=arrays_7 %}
139+
```scala
140+
-- Error: ----------------------------------------------------------------------
141+
3 | val arr = new Array[T]((xs.length + 1) / 2)
142+
| ^
143+
| No ClassTag available for T
144+
```
145+
{% endtab %}
146+
{% endtabs %}
79147

80148
What's required here is that you help the compiler out by providing some runtime hint what the actual type parameter of `evenElems` is. This runtime hint takes the form of a class manifest of type `scala.reflect.ClassTag`. A class manifest is a type descriptor object which describes what the top-level class of a type is. Alternatively to class manifests there are also full manifests of type `scala.reflect.Manifest`, which describe all aspects of a type. But for array creation, only class manifests are needed.
81149

82150
The Scala compiler will construct class manifests automatically if you instruct it to do so. "Instructing" means that you demand a class manifest as an implicit parameter, like this:
83151

84-
def evenElems[T](xs: Vector[T])(implicit m: ClassTag[T]): Array[T] = ...
152+
{% tabs arrays_8 class=tabs-scala-version %}
153+
{% tab 'Scala 2' for=arrays_8 %}
154+
```scala
155+
def evenElems[T](xs: Vector[T])(implicit m: ClassTag[T]): Array[T] = ...
156+
```
157+
{% endtab %}
158+
{% tab 'Scala 3' for=arrays_8 %}
159+
```scala
160+
def evenElems[T](xs: Vector[T])(using m: ClassTag[T]): Array[T] = ...
161+
```
162+
{% endtab %}
163+
{% endtabs %}
85164

86165
Using an alternative and shorter syntax, you can also demand that the type comes with a class manifest by using a context bound. This means following the type with a colon and the class name `ClassTag`, like this:
87166

88-
import scala.reflect.ClassTag
89-
// this works
90-
def evenElems[T: ClassTag](xs: Vector[T]): Array[T] = {
91-
val arr = new Array[T]((xs.length + 1) / 2)
92-
for (i <- 0 until xs.length by 2)
93-
arr(i / 2) = xs(i)
94-
arr
95-
}
167+
{% tabs arrays_9 class=tabs-scala-version %}
168+
{% tab 'Scala 2' for=arrays_9 %}
169+
```scala
170+
import scala.reflect.ClassTag
171+
// this works
172+
def evenElems[T: ClassTag](xs: Vector[T]): Array[T] = {
173+
val arr = new Array[T]((xs.length + 1) / 2)
174+
for (i <- 0 until xs.length by 2)
175+
arr(i / 2) = xs(i)
176+
arr
177+
}
178+
```
179+
{% endtab %}
180+
{% tab 'Scala 3' for=arrays_9 %}
181+
```scala
182+
import scala.reflect.ClassTag
183+
// this works
184+
def evenElems[T: ClassTag](xs: Vector[T]): Array[T] =
185+
val arr = new Array[T]((xs.length + 1) / 2)
186+
for i <- 0 until xs.length by 2 do
187+
arr(i / 2) = xs(i)
188+
arr
189+
```
190+
{% endtab %}
191+
{% endtabs %}
96192

97193
The two revised versions of `evenElems` mean exactly the same. What happens in either case is that when the `Array[T]` is constructed, the compiler will look for a class manifest for the type parameter T, that is, it will look for an implicit value of type `ClassTag[T]`. If such a value is found, the manifest is used to construct the right kind of array. Otherwise, you'll see an error message like the one above.
98194

99195
Here is some REPL interaction that uses the `evenElems` method.
100196

101-
scala> evenElems(Vector(1, 2, 3, 4, 5))
102-
res6: Array[Int] = Array(1, 3, 5)
103-
scala> evenElems(Vector("this", "is", "a", "test", "run"))
104-
res7: Array[java.lang.String] = Array(this, a, run)
197+
{% tabs arrays_10 %}
198+
{% tab 'Scala 2 and 3' for=arrays_10 %}
199+
```scala
200+
scala> evenElems(Vector(1, 2, 3, 4, 5))
201+
val res6: Array[Int] = Array(1, 3, 5)
202+
203+
scala> evenElems(Vector("this", "is", "a", "test", "run"))
204+
val res7: Array[java.lang.String] = Array(this, a, run)
205+
```
206+
{% endtab %}
207+
{% endtabs %}
105208

106209
In both cases, the Scala compiler automatically constructed a class manifest for the element type (first, `Int`, then `String`) and passed it to the implicit parameter of the `evenElems` method. The compiler can do that for all concrete types, but not if the argument is itself another type parameter without its class manifest. For instance, the following fails:
107210

108-
scala> def wrap[U](xs: Vector[U]) = evenElems(xs)
109-
<console>:6: error: No ClassTag available for U.
110-
def wrap[U](xs: Vector[U]) = evenElems(xs)
111-
^
211+
{% tabs arrays_11 class=tabs-scala-version %}
212+
{% tab 'Scala 2' for=arrays_11 %}
213+
```scala
214+
scala> def wrap[U](xs: Vector[U]) = evenElems(xs)
215+
<console>:6: error: No ClassTag available for U.
216+
def wrap[U](xs: Vector[U]) = evenElems(xs)
217+
^
218+
```
219+
{% endtab %}
220+
{% tab 'Scala 3' for=arrays_11 %}
221+
```scala
222+
-- Error: ----------------------------------------------------------------------
223+
6 |def wrap[U](xs: Vector[U]) = evenElems(xs)
224+
| ^
225+
| No ClassTag available for U
226+
```
227+
{% endtab %}
228+
{% endtabs %}
112229

113230
What happened here is that the `evenElems` demands a class manifest for the type parameter `U`, but none was found. The solution in this case is, of course, to demand another implicit class manifest for `U`. So the following works:
114231

115-
scala> def wrap[U: ClassTag](xs: Vector[U]) = evenElems(xs)
116-
wrap: [U](xs: Vector[U])(implicit evidence$1: scala.reflect.ClassTag[U])Array[U]
232+
{% tabs arrays_12 %}
233+
{% tab 'Scala 2 and 3' for=arrays_12 %}
234+
```scala
235+
scala> def wrap[U: ClassTag](xs: Vector[U]) = evenElems(xs)
236+
def wrap[U](xs: Vector[U])(implicit evidence$1: scala.reflect.ClassTag[U]): Array[U]
237+
```
238+
{% endtab %}
239+
{% endtabs %}
117240

118241
This example also shows that the context bound in the definition of `U` is just a shorthand for an implicit parameter named here `evidence$1` of type `ClassTag[U]`.
119242

‎_overviews/collections-2.13/equality.md

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,32 @@ The collection libraries have a uniform approach to equality and hashing. The id
1616

1717
It does not matter for the equality check whether a collection is mutable or immutable. For a mutable collection one simply considers its current elements at the time the equality test is performed. This means that a mutable collection might be equal to different collections at different times, depending on what elements are added or removed. This is a potential trap when using a mutable collection as a key in a hashmap. Example:
1818

19-
scala> import collection.mutable.{HashMap, ArrayBuffer}
20-
import collection.mutable.{HashMap, ArrayBuffer}
21-
scala> val buf = ArrayBuffer(1, 2, 3)
22-
buf: scala.collection.mutable.ArrayBuffer[Int] =
23-
ArrayBuffer(1, 2, 3)
24-
scala> val map = HashMap(buf -> 3)
25-
map: scala.collection.mutable.HashMap[scala.collection.
26-
mutable.ArrayBuffer[Int],Int] = Map((ArrayBuffer(1, 2, 3),3))
27-
scala> map(buf)
28-
res13: Int = 3
29-
scala> buf(0) += 1
30-
scala> map(buf)
31-
java.util.NoSuchElementException: key not found:
19+
{% tabs equality_1 %}
20+
{% tab 'Scala 2 and 3' for=equality_1 %}
21+
22+
```scala
23+
scala> import collection.mutable.{HashMap, ArrayBuffer}
24+
import collection.mutable.{HashMap, ArrayBuffer}
25+
26+
scala> val buf = ArrayBuffer(1, 2, 3)
27+
val buf: scala.collection.mutable.ArrayBuffer[Int] =
28+
ArrayBuffer(1, 2, 3)
29+
30+
scala> val map = HashMap(buf -> 3)
31+
val map: scala.collection.mutable.HashMap[scala.collection.
32+
mutable.ArrayBuffer[Int],Int] = Map((ArrayBuffer(1, 2, 3),3))
33+
34+
scala> map(buf)
35+
val res13: Int = 3
36+
37+
scala> buf(0) += 1
38+
39+
scala> map(buf)
40+
java.util.NoSuchElementException: key not found:
3241
ArrayBuffer(2, 2, 3)
42+
```
43+
44+
{% endtab %}
45+
{% endtabs %}
3346

3447
In this example, the selection in the last line will most likely fail because the hash-code of the array `buf` has changed in the second-to-last line. Therefore, the hash-code-based lookup will look at a different place than the one where `buf` was stored.

‎_overviews/collections-2.13/strings.md

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,30 @@ permalink: /overviews/collections-2.13/:title.html
1414

1515
Like arrays, strings are not directly sequences, but they can be converted to them, and they also support all sequence operations on strings. Here are some examples of operations you can invoke on strings.
1616

17-
scala> val str = "hello"
18-
str: java.lang.String = hello
19-
scala> str.reverse
20-
res6: String = olleh
21-
scala> str.map(_.toUpper)
22-
res7: String = HELLO
23-
scala> str drop 3
24-
res8: String = lo
25-
scala> str.slice(1, 4)
26-
res9: String = ell
27-
scala> val s: Seq[Char] = str
28-
s: Seq[Char] = hello
17+
{% tabs strings_1 %}
18+
{% tab 'Scala 2 and 3' for=strings_1 %}
19+
20+
```scala
21+
scala> val str = "hello"
22+
val str: java.lang.String = hello
23+
24+
scala> str.reverse
25+
val res6: String = olleh
26+
27+
scala> str.map(_.toUpper)
28+
val res7: String = HELLO
29+
30+
scala> str.drop(3)
31+
val res8: String = lo
32+
33+
scala> str.slice(1, 4)
34+
val res9: String = ell
35+
36+
scala> val s: Seq[Char] = str
37+
val s: Seq[Char] = hello
38+
```
39+
40+
{% endtab %}
41+
{% endtabs %}
2942

3043
These operations are supported by two implicit conversions. The first, low-priority conversion maps a `String` to a `WrappedString`, which is a subclass of `immutable.IndexedSeq`, This conversion got applied in the last line above where a string got converted into a Seq. The other, high-priority conversion maps a string to a `StringOps` object, which adds all methods on immutable sequences to strings. This conversion was implicitly inserted in the method calls of `reverse`, `map`, `drop`, and `slice` in the example above.

‎_overviews/collections-2.13/views.md

Lines changed: 155 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,21 @@ There are two principal ways to implement transformers. One is _strict_, that is
1818

1919
As an example of a non-strict transformer consider the following implementation of a lazy map operation:
2020

21-
def lazyMap[T, U](coll: Iterable[T], f: T => U) = new Iterable[U] {
22-
def iterator = coll.iterator map f
23-
}
21+
{% tabs views_1 class=tabs-scala-version %}
22+
{% tab 'Scala 2' for=views_1 %}
23+
```scala mdoc
24+
def lazyMap[T, U](iter: Iterable[T], f: T => U) = new Iterable[U] {
25+
def iterator = iter.iterator.map(f)
26+
}
27+
```
28+
{% endtab %}
29+
{% tab 'Scala 3' for=views_1 %}
30+
```scala
31+
def lazyMap[T, U](iter: Iterable[T], f: T => U) = new Iterable[U]:
32+
def iterator = iter.iterator.map(f)
33+
```
34+
{% endtab %}
35+
{% endtabs %}
2436

2537
Note that `lazyMap` constructs a new `Iterable` without stepping through all elements of the given collection `coll`. The given function `f` is instead applied to the elements of the new collection's `iterator` as they are demanded.
2638

@@ -30,42 +42,103 @@ To go from a collection to its view, you can use the `view` method on the collec
3042

3143
Let's see an example. Say you have a vector of Ints over which you want to map two functions in succession:
3244

33-
scala> val v = Vector(1 to 10: _*)
34-
v: scala.collection.immutable.Vector[Int] =
35-
Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
36-
scala> v map (_ + 1) map (_ * 2)
37-
res5: scala.collection.immutable.Vector[Int] =
38-
Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22)
45+
{% tabs views_2 class=tabs-scala-version %}
46+
{% tab 'Scala 2' for=views_2 %}
47+
48+
```scala
49+
scala> val v = Vector(1 to 10: _*)
50+
val v: scala.collection.immutable.Vector[Int] =
51+
Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
52+
53+
scala> v.map(_ + 1).map(_ * 2)
54+
val res5: scala.collection.immutable.Vector[Int] =
55+
Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22)
56+
```
57+
58+
{% endtab %}
59+
{% tab 'Scala 3' for=views_2 %}
60+
61+
```scala
62+
scala> val v = Vector((1 to 10)*)
63+
val v: scala.collection.immutable.Vector[Int] =
64+
Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
65+
66+
scala> v.map(_ + 1).map(_ * 2)
67+
val res5: scala.collection.immutable.Vector[Int] =
68+
Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22)
69+
```
70+
71+
{% endtab %}
72+
{% endtabs %}
3973

4074
In the last statement, the expression `v map (_ + 1)` constructs a new vector which is then transformed into a third vector by the second call to `map (_ * 2)`. In many situations, constructing the intermediate result from the first call to map is a bit wasteful. In the example above, it would be faster to do a single map with the composition of the two functions `(_ + 1)` and `(_ * 2)`. If you have the two functions available in the same place you can do this by hand. But quite often, successive transformations of a data structure are done in different program modules. Fusing those transformations would then undermine modularity. A more general way to avoid the intermediate results is by turning the vector first into a view, then applying all transformations to the view, and finally forcing the view to a vector:
4175

42-
scala> (v.view map (_ + 1) map (_ * 2)).to(Vector)
43-
res12: scala.collection.immutable.Vector[Int] =
44-
Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22)
76+
{% tabs views_3 %}
77+
{% tab 'Scala 2 and 3' for=views_3 %}
78+
79+
```scala
80+
scala> val w = v.view.map(_ + 1).map(_ * 2).to(Vector)
81+
val w: scala.collection.immutable.Vector[Int] =
82+
Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22)
83+
```
84+
85+
{% endtab %}
86+
{% endtabs %}
4587

4688
Let's do this sequence of operations again, one by one:
4789

48-
scala> val vv = v.view
49-
vv: scala.collection.IndexedSeqView[Int] = IndexedSeqView(<not computed>)
90+
{% tabs views_4 %}
91+
{% tab 'Scala 2 and 3' for=views_4 %}
92+
93+
```scala
94+
scala> val vv = v.view
95+
val vv: scala.collection.IndexedSeqView[Int] = IndexedSeqView(<not computed>)
96+
```
97+
98+
{% endtab %}
99+
{% endtabs %}
50100

51101
The application `v.view` gives you an `IndexedSeqView[Int]`, i.e. a lazily evaluated `IndexedSeq[Int]`. Like with `LazyList`,
52102
the `toString` operation of views does not force the view elements, that’s why the content of `vv` is shown as `IndexedSeqView(<not computed>)`.
53103

54104
Applying the first `map` to the view gives:
55105

56-
scala> vv map (_ + 1)
57-
res13: scala.collection.IndexedSeqView[Int] = IndexedSeqView(<not computed>)
106+
{% tabs views_5 %}
107+
{% tab 'Scala 2 and 3' for=views_5 %}
108+
109+
```scala
110+
scala> vv.map(_ + 1)
111+
val res13: scala.collection.IndexedSeqView[Int] = IndexedSeqView(<not computed>)
112+
```
113+
{% endtab %}
114+
{% endtabs %}
58115

59116
The result of the `map` is another `IndexedSeqView[Int]` value. This is in essence a wrapper that *records* the fact that a `map` with function `(_ + 1)` needs to be applied on the vector `v`. It does not apply that map until the view is forced, however. Let's now apply the second `map` to the last result.
60117

61-
scala> res13 map (_ * 2)
62-
res14: scala.collection.IndexedSeqView[Int] = IndexedSeqView(<not computed>)
118+
{% tabs views_6 %}
119+
{% tab 'Scala 2 and 3' for=views_6 %}
120+
121+
```scala
122+
scala> res13.map(_ * 2)
123+
val res14: scala.collection.IndexedSeqView[Int] = IndexedSeqView(<not computed>)
124+
```
125+
126+
{% endtab %}
127+
{% endtabs %}
63128

64129
Finally, forcing the last result gives:
65130

66-
scala> res14.to(Vector)
67-
res15: scala.collection.immutable.Vector[Int] =
68-
Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22)
131+
{% tabs views_7 %}
132+
{% tab 'Scala 2 and 3' for=views_7 %}
133+
134+
```scala
135+
scala> res14.to(Vector)
136+
val res15: scala.collection.immutable.Vector[Int] =
137+
Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22)
138+
```
139+
140+
{% endtab %}
141+
{% endtabs %}
69142

70143
Both stored functions get applied as part of the execution of the `to` operation and a new vector is constructed. That way, no intermediate data structure is needed.
71144

@@ -84,33 +157,87 @@ These operations are documented as “always forcing the collection elements”.
84157

85158
The main reason for using views is performance. You have seen that by switching a collection to a view the construction of intermediate results can be avoided. These savings can be quite important. As another example, consider the problem of finding the first palindrome in a list of words. A palindrome is a word which reads backwards the same as forwards. Here are the necessary definitions:
86159

87-
def isPalindrome(x: String) = x == x.reverse
88-
def findPalindrome(s: Seq[String]) = s find isPalindrome
160+
{% tabs views_8 %}
161+
{% tab 'Scala 2 and 3' for=views_8 %}
162+
163+
```scala
164+
def isPalindrome(x: String) = x == x.reverse
165+
def findPalindrome(s: Seq[String]) = s.find(isPalindrome)
166+
```
167+
168+
{% endtab %}
169+
{% endtabs %}
89170

90171
Now, assume you have a very long sequence words, and you want to find a palindrome in the first million words of that sequence. Can you re-use the definition of `findPalindrome`? Of course, you could write:
91172

92-
findPalindrome(words take 1000000)
173+
{% tabs views_9 %}
174+
{% tab 'Scala 2 and 3' for=views_9 %}
175+
```scala
176+
val palindromes = findPalindrome(words.take(1000000))
177+
```
178+
{% endtab %}
179+
{% endtabs %}
93180

94181
This nicely separates the two aspects of taking the first million words of a sequence and finding a palindrome in it. But the downside is that it always constructs an intermediary sequence consisting of one million words, even if the first word of that sequence is already a palindrome. So potentially, 999'999 words are copied into the intermediary result without being inspected at all afterwards. Many programmers would give up here and write their own specialized version of finding palindromes in some given prefix of an argument sequence. But with views, you don't have to. Simply write:
95182

96-
findPalindrome(words.view take 1000000)
183+
{% tabs views_10 %}
184+
{% tab 'Scala 2 and 3' for=views_10 %}
185+
```scala
186+
val palindromes = findPalindrome(words.view.take(1000000))
187+
```
188+
{% endtab %}
189+
{% endtabs %}
97190

98191
This has the same nice separation of concerns, but instead of a sequence of a million elements it will only construct a single lightweight view object. This way, you do not need to choose between performance and modularity.
99192

100193
After having seen all these nifty uses of views you might wonder why have strict collections at all? One reason is that performance comparisons do not always favor lazy over strict collections. For smaller collection sizes the added overhead of forming and applying closures in views is often greater than the gain from avoiding the intermediary data structures. A probably more important reason is that evaluation in views can be very confusing if the delayed operations have side effects.
101194

102195
Here's an example which bit a few users of versions of Scala before 2.8. In these versions the `Range` type was lazy, so it behaved in effect like a view. People were trying to create a number of actors like this:
103196

104-
val actors = for (i <- 1 to 10) yield actor { ... }
197+
{% tabs views_11 class=tabs-scala-version %}
198+
{% tab 'Scala 2' for=views_11 %}
199+
```scala
200+
val actors = for (i <- 1 to 10) yield actor { ... }
201+
```
202+
{% endtab %}
203+
{% tab 'Scala 3' for=views_11 %}
204+
```scala
205+
val actors = for i <- 1 to 10 yield actor { ... }
206+
```
207+
{% endtab %}
208+
{% endtabs %}
105209

106210
They were surprised that none of the actors was executing afterwards, even though the actor method should create and start an actor from the code that's enclosed in the braces following it. To explain why nothing happened, remember that the for expression above is equivalent to an application of map:
107211

108-
val actors = (1 to 10) map (i => actor { ... })
212+
{% tabs views_12 %}
213+
{% tab 'Scala 2 and 3' for=views_12 %}
214+
215+
```scala
216+
val actors = (1 to 10).map(i => actor { ... })
217+
```
218+
219+
{% endtab %}
220+
{% endtabs %}
109221

110222
Since previously the range produced by `(1 to 10)` behaved like a view, the result of the map was again a view. That is, no element was computed, and, consequently, no actor was created! Actors would have been created by forcing the range of the whole expression, but it's far from obvious that this is what was required to make the actors do their work.
111223

112224
To avoid surprises like this, the current Scala collections library has more regular rules. All collections except lazy lists and views are strict. The only way to go from a strict to a lazy collection is via the `view` method. The only way to go back is via `to`. So the `actors` definition above would now behave as expected in that it would create and start 10 actors. To get back the surprising previous behavior, you'd have to add an explicit `view` method call:
113225

114-
val actors = for (i <- (1 to 10).view) yield actor { ... }
226+
{% tabs views_13 class=tabs-scala-version %}
227+
{% tab 'Scala 2' for=views_13 %}
228+
229+
```scala
230+
val actors = for (i <- (1 to 10).view) yield actor { ... }
231+
```
232+
233+
{% endtab %}
234+
{% tab 'Scala 3' for=views_13 %}
235+
236+
```scala
237+
val actors = for i <- (1 to 10).view yield actor { ... }
238+
```
239+
240+
{% endtab %}
241+
{% endtabs %}
115242

116243
In summary, views are a powerful tool to reconcile concerns of efficiency with concerns of modularity. But in order not to be entangled in aspects of delayed evaluation, you should restrict views to purely functional code where collection transformations do not have side effects. What's best avoided is a mixture of views and operations that create new collections while also having side effects.

0 commit comments

Comments
 (0)
Please sign in to comment.