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

  • 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.

主站蜘蛛池模板: 唐河县| 临江市| 无为县| 赤壁市| 祁阳县| 彭州市| 贵阳市| 洛南县| 龙川县| 泰来县| 石柱| 邵东县| 左云县| 抚松县| 马尔康县| 东海县| 开江县| 文水县| 民勤县| 五台县| 青阳县| 邹城市| 贵南县| 海宁市| 灌南县| 霞浦县| 淮北市| 黑龙江省| 西林县| 塔城市| 定兴县| 肇州县| 紫云| 平原县| 神农架林区| 沈阳市| 普洱| 临颍县| 平舆县| 台安县| 灵山县|