- 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.
推薦閱讀
- Mastering Concurrency Programming with Java 8
- ClickHouse性能之巔:從架構設計解讀性能之謎
- SoapUI Cookbook
- Mastering Entity Framework
- Apache Spark 2 for Beginners
- 面向STEM的Scratch創新課程
- SQL Server 2012數據庫管理與開發項目教程
- Cocos2d-x學習筆記:完全掌握Lua API與游戲項目開發 (未來書庫)
- Advanced Oracle PL/SQL Developer's Guide(Second Edition)
- Python數據結構與算法(視頻教學版)
- Tableau 10 Bootcamp
- C# and .NET Core Test Driven Development
- Kotlin極簡教程
- OpenCV 3.0 Computer Vision with Java
- After Effects CC技術大全