- 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.
推薦閱讀
- Java異步編程實戰
- C#編程入門指南(上下冊)
- Apache Spark 2.x Machine Learning Cookbook
- Java應用開發與實踐
- Spring Cloud、Nginx高并發核心編程
- Interactive Applications Using Matplotlib
- Terraform:多云、混合云環境下實現基礎設施即代碼(第2版)
- 打開Go語言之門:入門、實戰與進階
- Azure Serverless Computing Cookbook
- UI設計基礎培訓教程(全彩版)
- Visual Basic語言程序設計基礎(第3版)
- Mastering SciPy
- Java Hibernate Cookbook
- 軟件設計模式(Java版)
- C語言程序設計實驗指導