Search code examples
scalaparametersimplicitfunction-literal

How to define a function that takes a function literal (with an implicit parameter) as an argument?


I want to be able to do something on these lines (won't compile):

def logScope(logger:Logger)(operation: (implicit l:Logger) => Unit) {/* code */ operation(logger) /* code */} 
def operationOne(implicit logger:Logger) {/**/}
def operationTwo(implicit logger:Logger) {/**/}

And then use it like so:

logScope(new ConsoleLogger){logger =>
    operationOne
    operationTwo
    }

But the nearest I've come to a working solution is this:

def logScope(logger:Logger)(operation: Logger => Unit) {/* code */ operation(logger) /* code */} 
def operationOne(implicit logger:Logger) {/**/}
def operationTwo(implicit logger:Logger) {/**/}

/* other code */

logScope(new ConsoleLogger){logger =>
    implicit val l = logger
    operationOne
    operationTwo
    }

I don't think the language currently allows such constructs, but still, any suggestions or workarounds to achieve similar results?


minor update: I've created a gist with a slightly expanded version of the above code with a couple of attempts at simulating this kind of literal. As of now, CheatEx's version is the best one.


Solution

  • In your second example try this:

    logScope(Logger()) { implicit logger =>
      operationOne
    }
    

    It should work fine. The logic here is that 'implicit' is an attribute of particular value inside closure, not a part of the closure's interface.