2

in scala when I create a trait with implicit def fields, how can I use them why should I add the implicit keyword to the def keyword?

trait MyXXXProtocol extends Logging {

  implicit def actor: ActorSystem
  implicit def materializer: Materializer
  implicit def executor: ExecutionContextExecutor


}

any examples will really help.

Tal Avissar
  • 10,088
  • 6
  • 45
  • 70

1 Answers1

4

Read this first, which talks about what the difference between using val and def inside a trait is in Scala. here.

You would use that pattern when your trait contains concrete implementation of some kind that relies on these implicits being there, but you want the final implementors of your trait to be the ones that specify concrete values for those implicits.

trait MyXXXProtocol extends Logging {

  implicit def actor: ActorSystem
  implicit def materializer: Materializer
  implicit def executor: ExecutionContextExecutor

  def test(input: String): Unit = {
    // let's pretend this is valid
    actor.props("bla").send(input)
  }

This becomes useful if for instance the signature of send is something like this:

def send(input: String)(
  implicit system: ActorSystem,
  materializer: FlowMaterializer
): Unit = ...

It's useful because you've now created a template but it's up to concrete implementors to supply the implicit system in which these things will execute, you are forwarding those implicits such that you can have some implementation defined where they are required, but you can supply a real implicit later.

Community
  • 1
  • 1
flavian
  • 28,161
  • 11
  • 65
  • 105
  • As the comments there point out, your first paragraph is wrong: what matters isn't whether the abstract member is declared as `val` or `def` but whether it's _implemented_ as a non-lazy `val` (or a `def` which accesses non-lazy `val`s). – Alexey Romanov May 18 '17 at 10:49
  • @AlexeyRomanov Correct, I rushed to answer and wrote a fairytale :) – flavian May 18 '17 at 12:14