difference between map and flatMap in scala -
what difference between map , flatmap? in can
1 5 map(c => println(c))
but not
1 5 flatmap(c => println(c))
on other hand, works
def h(i: int) = if (i >= 2) some(i) else none 1 5 flatmap(h)
i understand flatmap map , flatten, not sure when map can used , when flatmap can used.
let's see signature of flatmap.
def flatmap[b](f: (int) ⇒ gentraversableonce[b]): traversableonce[b]
and signature of map
def map[b](f: (a) ⇒ b): indexedseq[b]
you can see result type of f
must gentraversableonce[b]
flatmap
. there's no restriction in result type of f
map
.
the result type of println(x)
unit
, result type of x+2
int
. since both not implement gentraversableonce[b]
, cannot flatmap(x=>println(x))
nor flatmap(x=>x+2)
.
on other hand some(i)
, none
have type of option[int]
, can implicitly converted iterable[int]
source
the signature of iterable
trait iterable[+a] extends traversable[a]
and traversable is
trait traversable[+a] .. traversableonce[a]`
and traversableonce is
trait traversableonce[+a] extends gentraversableonce[a]
hence option[int]
implements gentraversableonce[int]
can use result of flatmap[int]
Comments
Post a Comment