Learn about the use of the for expression in Scala today.
Package Scala.learn
Case Class Persons (name:string,ismale:boolean,children:persons*)
Object Test_85 {
def main (args:array[string]) {
Val Lauren = Persons ("Lauren", false)
Val Rocky = Persons ("Rocky", True)
Val Vivian = Persons ("Vivian", False,lauren,rocky)
Val persons = List (Lauren,rocky,vivian)
Val result = Persons.filter {Person ~ =!person.ismale}.flatmap {Person ~ = (Person.children.map {child = (per Son.name,child.name)})}
println (Result)
Val Forresult = for (person<-persons;if!person.ismale;child <-person.children) yield (person.name,child.name)
println (Result)
}
}
We can see that our first method uses the high-order function to filter the data, first through the filter to select the Famale, and then through the Flatmap, each element of the persons is calculated one by one: will enter the person to select their children, Then children the map operation again to get a list of the person's name and the name of the person's children.
And the same function, we can express it simply by the For loop.
First, the person iterates through the persons and then, through the IF control statement, picks out Famale, and then the child iterates through the children of the selected person. Finally, yield is formed to form the result list.
In fact, through the source code, we can see that the For loop is also the result of a combination of map calculation and flatmap calculation.
Share more of the Scala resources:
Baidu Cloud Disk: http://pan.baidu.com/s/1gd7133t
Micro Cloud Disk: http://share.weiyun.com/047efd6cc76d6c0cb21605cfaa88c416
360 Cloud Disk: Http://yunpan.cn/cQN9gvcKXe26M (extract code: 13CD)
Information from DT Big Data Dream Factory public account: Dt_spark
Follow the account for more information about Scala learning
85th: The powerful expressive battle of the for expression in Scala