高阶函数 filter 源码分析

package com.dt.scala.forexpression


case class Person(name: String, isMale: Boolean, children: Person*)

object For_Expressive {


  def main(args: Array[String]) {

    val lauren = Person("Lauren", false)

    val rocky = Person("Rocky", true)

    val vivian = Person("Vivian", false, lauren, rocky)

    val persons = List(lauren, rocky, vivian)

    

    val result = persons filter (person => !person.isMale) flatMap(person => 

      (person.children map (child => (person.name, child.name))))

    println(result)

    

    val forResult = for (person <- persons; if !person.isMale; child <- person.children) 

      yield (person.name, child.name)

    println(forResult)

    

  }


}


flatMap, 压扁,是将2个集合合并。

用for循环一样能实现示例中的功能,表达力更清晰。

for循环背后是flatMap的方式,跳转代码能直接看到flatMap。强大的功能。