How does scala.collection.TraversableView.NoBuilder work? -


i've read

i think have bit of handle on canbuildfrom.

but @ source traversableview, , see this:

object traversableview {   class nobuilder[a] extends builder[a, nothing] {     def +=(elem: a): this.type =     def iterator: iterator[a] = iterator.empty     def result() = throw new unsupportedoperationexception("traversableview.builder.result")     def clear() {}   }   type coll = traversableview[_, c] forsome {type c <: traversable[_]}   implicit def canbuildfrom[a]: canbuildfrom[coll, a, traversableview[a, traversable[_]]] =     new canbuildfrom[coll, a, traversableview[a, traversable[_]]] {       def apply(from: coll) = new nobuilder       def apply() = new nobuilder     } } 

how traversableview work this? seems there nothing happening here (nobuilder seems aptly named).

could explain (1) function nobuilder plays here , (2) how map, filter, etc. can still work?

the nobuilder exists clients can treat scala views if normal collections when transforming them. dummy implementation allows traversableview extend traversable , call methods map without knowing if collection view or normal collection.

longer explanation

when call map, flatmap or scanleft (called transformer operations) on scala collection, canbuildfrom implicit argument automatically resolved. canbuildfrom object abstract factory builder objects.

most scala collections use builders add elements += , produce new collection calling result on buidler. e.g. given builder object b, map this:

def map[s, that](f: t => s)(implicit cbf: canbuildfrom[repr, s, that]) = {   val b: builder[s, that] = cbf(this)   (x <- this) b += f(x)   b.result } 

transformer operations on views not instantiate new collection. instead, create lazy view. example, map this:

def map[s, that](f: t => s)(implicit cbf: canbuildfrom[repr, s, that]) = new traversableview {   def foreach[u](forfunc: t => u): unit = (x <- self) forfunc(f(x)) } 

note map on view has same signature, not call += , result on builder. thus, nobuilder used in views not need store elements or return collection, dummy methods never called.

the same signature allows writing in client code:

def foo(xs: traversable[int]) = xs.map(_ + 1) foo(0 until 100) foo((0 until 100).view) 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -