- 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.
- Web開發的貴族:ASP.NET 3.5+SQL Server 2008
- Mastering Yii
- JavaScript+Vue+React全程實例
- 概率成形編碼調制技術理論及應用
- Haskell Data Analysis Cookbook
- Android項目實戰:手機安全衛士開發案例解析
- Learning JavaScript Data Structures and Algorithms(Second Edition)
- Nagios Core Administration Cookbook(Second Edition)
- 零基礎看圖學ScratchJr:少兒趣味編程(全彩大字版)
- 計算語言學導論
- 大學計算機應用基礎(Windows 7+Office 2010)(IC3)
- Kotlin進階實戰
- 產品架構評估原理與方法
- 跟小樓老師學用Axure RP 9:玩轉產品原型設計
- HTML5程序開發范例寶典