码迷,mamicode.com
首页 > 其他好文 > 详细

scala map和flatMap

时间:2017-08-04 20:36:35      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:int   type   logs   mat   except   style   class   val   cas   

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)

 

scala map和flatMap

标签:int   type   logs   mat   except   style   class   val   cas   

原文地址:http://www.cnblogs.com/huanhuanang/p/7286753.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!