map和flatMap
scala> val a = Seq(1,2,3,6,4) a: Seq[Int] = List(1, 2, 3, 6, 4) scala> val b = a.flatMap(f=>{ | try{ | Some(f/(f-1)) | }catch{ | case e:Exception=>None | } | }) b: Seq[Int] = List(2, 1, 1, 1) scala> val b = a.map(f=>{ | try{ | Some(f/(f-1)) | }catch{ | case e:Exception=>None | } | }) b: Seq[Option[Int]] = List(None, Some(2), Some(1), Some(1), Some(1))
flatMap类型需要一致
scala> val d = a.flatMap(f=>{ | try{ | f/(f-1) | }catch{ | case e:Exception=>None | } | }) <console>:33: error: type mismatch; found : Int required: scala.collection.GenTraversableOnce[?] f/(f-1) ^ scala> val d = a.map(f=>{ | try{ | f/(f-1) | }catch{ | case e:Exception=>None | } | }) d: Seq[Any] = List(None, 2, 1, 1, 1)
时间: 2024-10-06 13:17:05