- 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.
推薦閱讀
- The DevOps 2.3 Toolkit
- Progressive Web Apps with React
- Android和PHP開發(fā)最佳實(shí)踐(第2版)
- SpringMVC+MyBatis快速開發(fā)與項(xiàng)目實(shí)戰(zhàn)
- Maven Build Customization
- 數(shù)據(jù)結(jié)構(gòu)案例教程(C/C++版)
- Unity 2D Game Development Cookbook
- C語(yǔ)言程序設(shè)計(jì)實(shí)驗(yàn)指導(dǎo) (第2版)
- Machine Learning for OpenCV
- Android Studio開發(fā)實(shí)戰(zhàn):從零基礎(chǔ)到App上線 (移動(dòng)開發(fā)叢書)
- Scrapy網(wǎng)絡(luò)爬蟲實(shí)戰(zhàn)
- HTML5移動(dòng)前端開發(fā)基礎(chǔ)與實(shí)戰(zhàn)(微課版)
- JavaScript前端開發(fā)基礎(chǔ)教程
- Java與Android移動(dòng)應(yīng)用開發(fā):技術(shù)、方法與實(shí)踐
- INSTANT Jsoup How-to