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

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.

主站蜘蛛池模板: 新昌县| 长武县| 滨州市| 丹巴县| 鄯善县| 高邮市| 无锡市| 桐乡市| 德令哈市| 永昌县| 启东市| 晋州市| 邻水| 慈利县| 长治县| 柳州市| 启东市| 彭山县| 罗甸县| 高台县| 连山| 延安市| 本溪市| 蓝山县| 保定市| 南汇区| 尉氏县| 吉安市| 桑植县| 琼海市| 北流市| 中方县| 常山县| 商南县| 双牌县| 石柱| 迁安市| 德安县| 顺义区| 商水县| 仪陇县|