85th: The powerful expressive battle of the for expression in Scala

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.