
上QQ阅读APP看书,第一时间看更新
The for yield expressions
Here's an example of a for yield expression where we're listing the names of winners. The criteria for winning a prize is the age, which should be more than 20:
object ForYieldExpressions extends App {
val person1 = Person("Albert", 21, 'm')
val person2 = Person("Bob", 25, 'm')
val person3 = Person("Cyril", 19, 'f')
val persons = List(person1, person2, person3)
val winners = for {
person <- persons
age = person.age
name = person.name
if age > 20
} yield name
winners.foreach(println)
case class Person(name: String, age: Int, gender: Char)
}
The following is the result:
Albert
Bob
Here, yield does the trick and results in a list of people with satisfying criteria. That's how for yield expressions work in Scala.
But these iterations are not what Scala or any other functional programming language recommends. Let's check out why this is and the alternative to iterative loops.