I struggle to apply the idea of implicit
in Scala to Akka Streams.
According to http://docs.scala-lang.org/overviews/core/implicit-classes.html, the basic concept of an implicit
class in Scala is that for 5 times prinln("foo")
an object of IntWithTimes
is created, making the method times
implicitly available through importing Helpers._
.
object Helpers {
implicit class IntWithTimes(x: Int) {
def times[A](f: => A): Unit = {
def loop(current: Int): Unit =
if(current > 0) {
f
loop(current - 1)
}
loop(x)
}
}
}
Let's consider the following example:
val g = RunnableGraph.fromGraph(GraphDSL.create() {
implicit builder: GraphDSL.Builder[Unit] =>
import GraphDSL.Implicits._
val in = Source(1 to 100)
val flow = Flow[Int].map(_ + 1)
val out = Sink.foreach(println)
in ~> flow ~> out
ClosedShape
})
g.run()
Obviously being new to Scala and Akka, my unsatisfying theory so far is that using create()
of GraphDSL
creates a RunnableGraph
by passing the Builder
into it.
Why does it have to be marked as implicit
? If left away, the ~>
operators cannot be resolved anymore - even though GraphDSL.Implicits._
is explicitly imported.