Skip to content

Instantly share code, notes, and snippets.

@davidandrzej
Created June 19, 2013 18:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidandrzej/5816439 to your computer and use it in GitHub Desktop.
Save davidandrzej/5816439 to your computer and use it in GitHub Desktop.
Example illustrating "lazy val" initialization when the RHS fails by throwing an Exception.
//
// If a "lazy val" initialization fails, the val is not initialized
// to anything and subsequent calls re-evaluate the RHS
//
object LazyRetry extends App {
class ServiceFactory() {
// Only returns a value after two failures
// (simulate waiting for service availability)
var tries = 0
private def _getService(): String = {
if(tries <= 1) {
tries += 1
throw new RuntimeException("Service not ready!")
}
else {
"ServiceOKGuy"
}
}
// Expose "service" to caller via lazy-initialized getter
lazy val service = _getService()
def getService() = service
}
val factory = new ServiceFactory()
def loadService() = {
// Print the result, or the Exception message
try {
println(factory.getService())
}
catch { case e: Throwable => println(e.getMessage) }
}
//
// The lazy val is not initialized until
// the function evaluation succeeds
//
loadService() // Service not ready!
loadService() // Service not ready!
loadService() // ServiceOKGuy
loadService() // ServiceOKGuy
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment