Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 486
LastContrarian Avatar asked Nov 23 '25 04:11

LastContrarian


1 Answers

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.

like image 174
CheatEx Avatar answered Nov 24 '25 18:11

CheatEx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!