Created
August 15, 2011 20:27
-
-
Save LastContrarian/1147757 to your computer and use it in GitHub Desktop.
Attempts at simulating a function literal with an implicit parameter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object ImplicitParamTest | |
{ | |
trait Logger | |
{ | |
def open() | |
def log(message:String) | |
def close() | |
} | |
final class ConsoleLogger extends Logger | |
{ | |
override def open() { println("console:open") } | |
override def log(message:String) { println("console:" + message) } | |
override def close() { println("console:close\n") } | |
} | |
final class FileLogger extends Logger | |
{ | |
override def open { println("file:open") } | |
override def log(message:String) { println("file:" + message) } | |
override def close { println("file:close\n") } | |
} | |
def operationOne(implicit logger:Logger) { logger.log("1st operation") } | |
def operationFive(implicit logger:Logger) { logger.log("5th operation") } | |
def operationForty(implicit logger:Logger, throwException:Boolean = false) { logger.log("40th operation"); if (throwException) throw new Exception } | |
def operationHundred(implicit logger:Logger) { logger.log("100th operation") } | |
def logScope(logger:Logger)(operation: Logger => Unit) | |
{ | |
try | |
{ | |
logger.open() | |
logger.log("begin log") | |
operation(logger) | |
} | |
catch | |
{ | |
case _ => logger.log("Exception!") | |
} | |
finally | |
{ | |
logger.log("end log") | |
logger.close() | |
} | |
} | |
def main(args:Array[String]) = | |
{ | |
logScope(new FileLogger){logger => | |
logger.log("First way: provide arguments") | |
operationOne(logger) | |
operationFive(logger) | |
operationForty(logger, true) | |
operationHundred(logger) | |
} | |
logScope(new ConsoleLogger){logger => | |
logger.log("Second way: assign to a local implicit value") | |
implicit val l = logger | |
operationOne | |
operationFive | |
operationForty | |
operationHundred | |
} | |
def thirdWay(implicit logger:Logger) = { | |
logger.log("Third way: define a function with an implicit parameter") | |
operationOne | |
operationFive | |
operationForty | |
operationHundred | |
} | |
logScope(new ConsoleLogger){logger => thirdWay(logger)} | |
logScope(new FileLogger){implicit logger => | |
logger.log("Fourth way: mark the parameter as implicit inside the function literal") | |
operationOne | |
operationFive | |
operationForty | |
operationHundred | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment