functional programming - Implicit class in Scala -
i have following piece of code.i have confirm whether way how works..can provide explanation this
object implicits { implicit class richseq[a](val xs:seq[a]) { def mapd[b](function:a => b):seq[b] = xs.map(function) } } this abstraction on map can use sequence. if import implicits.richseq can use methods on seq[a] convert seq[a] richseq[a].
import implicits.richseq._ val xs:seq[int] = seq(22,33) val output:seq[int] = xs.mapd(_+22) i want know how works because when use mapd on type seq[a] search implicit conversion seq[a] richseq[a].where find implicit conversion implicit class?
does expand implicit class like:
implicit def richseq[a](val xs:seq[a]) = new richseq(xs)
i think might doing stuff inside.does ne1 know this?
an implicit class shorthand for
class foo(a: a) implicit def pimpmya(a: a) = new foo(a) you can annotate class implicit if constructor takes 1 non-implicit parameter.
here's relevant doc can read more it: http://docs.scala-lang.org/overviews/core/implicit-classes.html
in specific example, means seq[a] can implicitly lifted richseq[a].
the compiler find implicit because imported it, it's available in scope.
you can see actual java output of code
val x = seq(1, 2, 3) x.mapd(_ + 22) by using scala repl option -xprint:typer. here's relevant bit of output
$line3.$read.$iw.$iw.implicits.richseq[int]($line3.$read.$iw.$iw.x).mapd[int](((x$1: int) => x$1.+(22))); which after polishing equivalent to
implicits.richseq(x).mapd(x$1 => x$1 + 22) as side note, have import implicits._. exact implicit resolutions rules, can refer where scala implicits?
Comments
Post a Comment