public

Attempts at simulating a function literal with an implicit parameter

  • Download Gist
ImplicitParamTest.scala
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
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
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.