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

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.

主站蜘蛛池模板: 大方县| 清丰县| 广汉市| 松原市| 鄂伦春自治旗| 乌拉特前旗| 连州市| 广西| 陇川县| 临沭县| 章丘市| 合川市| 临清市| 洞口县| 东丰县| 张掖市| 科尔| 尼玛县| 浦县| 山东省| 武山县| 揭阳市| 凤冈县| 松阳县| 舟山市| 吴忠市| 商南县| 麻江县| 临沂市| 长沙县| 温州市| 大安市| 西乌| 汝城县| 抚松县| 红原县| 梅河口市| 民乐县| 调兵山市| 耒阳市| 安义县|