September 2018
Intermediate to advanced
398 pages
9h 43m
English
We can go a bit further and delay the evaluation of function arguments. A by-name parameter is like a function that does not take any argument. This way, it only gets evaluated when the function's body requires it.
Say that you have an application that loads its configuration from a file or a database. You want the application to start as fast as possible, and so you decide to use lazy val to load a greeting message on demand, as shown in the following code:
object AppConfig { lazy val greeting: String = { println("Loading greeting") "Hello " } }
Note that for the sake of brevity we haven't actually loaded anything here—just imagine that we did.
If we then want to use the greeting variable in a function but keep delaying ...
Read now
Unlock full access