Created
June 19, 2013 18:04
-
-
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.
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
// | |
// 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