Skip to content

Commit 329ab5d

Browse files
authored
tour: improve text about for comprehensions (#1688)
this is my own rework of the earlier PR #1657
1 parent 17557b3 commit 329ab5d

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

_tour/for-comprehensions.md

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,20 @@ Here's an example:
1818
```tut
1919
case class User(name: String, age: Int)
2020
21-
val userBase = List(User("Travis", 28),
21+
val userBase = List(
22+
User("Travis", 28),
2223
User("Kelly", 33),
2324
User("Jennifer", 44),
2425
User("Dennis", 23))
2526
26-
val twentySomethings = for (user <- userBase if (user.age >=20 && user.age < 30))
27+
val twentySomethings =
28+
for (user <- userBase if user.age >=20 && user.age < 30)
2729
yield user.name // i.e. add this to a list
2830
2931
twentySomethings.foreach(name => println(name)) // prints Travis Dennis
3032
```
31-
The `for` loop used with a `yield` statement actually creates a `List`. Because we said `yield user.name`, it's a `List[String]`. `user <- userBase` is our generator and `if (user.age >=20 && user.age < 30)` is a guard that filters out users who are not in their 20s.
33+
34+
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.
3235

3336
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`:
3437

0 commit comments

Comments
 (0)