官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 乐东| 民权县| 亚东县| 太康县| 兴文县| 越西县| 扎鲁特旗| 县级市| 大竹县| 镇巴县| 巍山| 陵水| 迭部县| 龙胜| 英吉沙县| 泽库县| 黄梅县| 宁津县| 江口县| 肥东县| 安化县| 孟州市| 正镶白旗| 泸溪县| 墨江| 汉源县| 定远县| 和平区| 天全县| 康保县| 凤冈县| 进贤县| 娱乐| 仪陇县| 康平县| 清新县| 文化| 鱼台县| 昆山市| 齐河县| 阳春市|