- Learning Scala Programming
- Vikash Sharma
- 223字
- 2021-06-30 19:07:55
The for expressions
We've seen the for loops, and how simple it is to use them in Scala. There's much more we can do with the for syntax. Here's an example:
object ForExpressions 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)
for {
person <- persons
age = person.age
name = person.name
if age > 20 && name.startsWith("A")
} {
println(s"Hey ${name} You've won a free Gift Hamper.")
}
case class Person(name: String, age: Int, gender: Char)
}
The following is the result:
Hey Albert You've won a free Gift Hamper.
In the preceding example, we used a generator, definitions, and filters in the for expression. We used a for expression on a list of persons. We proposed a gift hamper for a person whose name starts with A and who is older than 20 years of age.
The first expression in for is a generator expression which generates a new person from the persons list and assigns to person. Second is age and name definitions. Then finally we apply filters using the if statement to put conditions for our winner:

What if we want a couple more prizes for our people. In that case we may want to get a sub list of winners. That's possible by introducing yield.
- INSTANT Mock Testing with PowerMock
- 手機(jī)安全和可信應(yīng)用開發(fā)指南:TrustZone與OP-TEE技術(shù)詳解
- 計(jì)算機(jī)網(wǎng)絡(luò)
- Rust編程:入門、實(shí)戰(zhàn)與進(jìn)階
- 程序員面試筆試寶典
- 數(shù)據(jù)結(jié)構(gòu)習(xí)題精解(C語言實(shí)現(xiàn)+微課視頻)
- Magento 2 Development Cookbook
- Scratch 3游戲與人工智能編程完全自學(xué)教程
- JavaScript動(dòng)態(tài)網(wǎng)頁開發(fā)詳解
- 微服務(wù)架構(gòu)深度解析:原理、實(shí)踐與進(jìn)階
- Learning AWS
- 創(chuàng)意UI:Photoshop玩轉(zhuǎn)APP設(shè)計(jì)
- Python函數(shù)式編程(第2版)
- PowerDesigner 16 從入門到精通
- C#程序設(shè)計(jì)基礎(chǔ)入門教程