scala - Understanding flatMap declaration in List -
i looked @ list.flatmap
declaration , kind of surprised this.
final override def flatmap[b, that](f: => gentraversableonce[b]) (implicit bf: canbuildfrom[list[a], b, that]):
where object list
defines:
implicit def canbuildfrom[a]: canbuildfrom[coll, a, list[a]] = reusablecbf.asinstanceof[genericcanbuildfrom[a]]
so, if invoke flatmap
on list
list
, don't see point in that
type if deduced list[b]
(because of implicit
).
so, if invoke
flatmap
onlist[a]
list[a]
, don't see point inthat
type if deducedlist[b]
one thing you're missing flatmap
isn't defined on list[+a]
. inherited traversablelike
, trait used of scalas collections. each of them can supply implicit canbuildfrom
may overridden supply different resulting collection.
if want little taste of can custom canbuildfrom
:
scala> :pa // entering paste mode (ctrl-d finish) import scala.collection.generic.canbuildfrom import scala.collection.immutable._ import scala.collection.mutable import scala.{list, vector} implicit val listtovectorcbf = new canbuildfrom[list[int], int, vector[int]] { override def apply(from: list[int]): mutable.builder[int, vector[int]] = this.apply() override def apply(): mutable.builder[int, vector[int]] = vector.newbuilder } // exiting paste mode, interpreting. scala> list(1,2,3).flatmap(list(_)) res6: vector[int] = vector(1, 2, 3)
Comments
Post a Comment