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
twentySomethings.foreach(println) // prints Travis Dennis
33
35
```
36
+
{% endtab %}
37
+
38
+
{% tab 'Scala 3' for=for-comprehensions-01 %}
39
+
```scala
40
+
caseclassUser(name: String, age: Int)
41
+
42
+
valuserBase=List(
43
+
User("Travis", 28),
44
+
User("Kelly", 33),
45
+
User("Jennifer", 44),
46
+
User("Dennis", 23))
47
+
48
+
valtwentySomethings=
49
+
for user <- userBase if user.age >=20&& user.age <30
50
+
yield user.name // i.e. add this to a list
51
+
52
+
twentySomethings.foreach(println) // prints Travis Dennis
53
+
```
54
+
{% endtab %}
55
+
{% endtabs %}
56
+
34
57
35
58
A `for` loop with a `yield` statement returns a result, the container type of which is determined by the first generator. `user <- userBase` is a `List`, and because we said `yield user.name` where `user.name` is a `String`, the overall result is a `List[String]`. And `if user.age >=20 && user.age < 30` is a guard that filters out users who are not in their twenties.
36
59
37
60
Here is a more complicated example using two generators. It computes all pairs of numbers between `0` and `n-1` whose sum is equal to a given value `v`:
Here `n == 10` and `v == 10`. On the first iteration, `i == 0` and `j == 0` so `i + j != v` and therefore nothing is yielded. `j` gets incremented 9 more times before `i` gets incremented to `1`. Without the `if` guard, this would simply print the following:
@@ -57,6 +101,8 @@ Note that comprehensions are not restricted to lists. Every datatype that suppor
57
101
58
102
You can omit `yield` in a comprehension. In that case, comprehension will return `Unit`. This can be useful in case you need to perform side-effects. Here's a program equivalent to the previous one, but without using `yield`:
0 commit comments