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

  • Learning Scala Programming
  • Vikash Sharma
  • 139字
  • 2021-06-30 19:07:55

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.

主站蜘蛛池模板: 阳春市| 博爱县| 和林格尔县| 广平县| 北辰区| 彭水| 东方市| 信宜市| 长岭县| 久治县| 甘肃省| 武鸣县| 黔东| 嘉禾县| 灵丘县| 田阳县| 北京市| 聊城市| 东源县| 安康市| 闸北区| 丰台区| 德州市| 会宁县| 淄博市| 井冈山市| 广西| 瑞金市| 普安县| 印江| 青河县| 本溪市| 肥城市| 白玉县| 思南县| 西乌珠穆沁旗| 沈丘县| 上饶县| 盱眙县| 肇州县| 迁西县|