'How to provide implicit argument to code block without explicitly creating it

I have a utility object SideEffects, which is passed to a function as implicit argument. It collects all non-db effects to run if my db transaction was successed.

def someDbAction(implicit se: SideEffects) {
  ...
  se.add {doSomethingNonDbLike()}
  ...
}

The simple way to use this util is to write something like this:

implicit val se = new SideEffects()
db.run(someDbAction().transactionally).flatMap(se.run)

And I want to write something like this:

SideEffects.run {
  someDbAction()
}

Is it possible to do it? Just can't make it work.



Solution 1:[1]

I don't understand why your someDbAction (or anything at all for that matter!) needs implicit parameter.

Going by your "I want to write ...", it looks like you want this:

    object SideEffects() { 
       val se = new SideEffects
       def run[T](action: => T) = 
          db.run(action).transactionally.flatMap(se.run())
    }

Then SideEffects.run { someDbAction() } (or just SideEffects.run(someDbAction)) does exactly what you wanted.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dima