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

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.

主站蜘蛛池模板: 泰安市| 泸西县| 永修县| 平潭县| 定陶县| 保亭| 舞钢市| 岗巴县| 海南省| 阿拉善盟| 密云县| 施甸县| 凤台县| 昌宁县| 盐山县| 萍乡市| 广水市| 遵义市| 江山市| 光山县| 安宁市| 孟连| 兰西县| 惠东县| 错那县| 邮箱| 伽师县| 舟曲县| 宁强县| 南宁市| 高州市| 铁岭县| 上饶市| 九龙县| 马关县| 蕉岭县| 尤溪县| 武山县| 乃东县| 宿松县| 富民县|