map和flatmap的区别---scala

看下面的例子:

abstract class List[T]{
  def map[U](f: T => U): List[U] = this match {
    case first :: last = f(first) :: last.map(f)
    case Nil = Nil
 }

  def flatMap[U](f: T => List[U]): List[U] = this match{
    case x:: xs => f(x) ++ xs.flatMap(f)
    case Nil => Nil
  }
}

总结:

1. map会将每一条输入映射为一个新对象。{苹果,梨子}.map(去皮) = {去皮苹果,去皮梨子} 其中: “去皮”函数的类型为:A => B

2.flatMap包含两个操作:会将每一个输入对象输入映射为一个新集合,然后把这些新集合连成一个大集合。 {苹果,梨子}.flatMap(切碎) = {苹果碎片1,苹果碎片2,梨子碎片1,梨子碎片2} 其中: “切碎”函数的类型为: A => List<B>

猜你喜欢

转载自blog.csdn.net/S_Running_snail/article/details/85095724
今日推荐