Friday, September 18, 2009

Lazy Val

One nice feature built into Scala are "lazy val" values. Essentially they are the lazy initialization pattern that is very commonly implemented in Java programs (and very commonly incorrectly implemented). When a val is declared with the lazy modifier the right-hand side of the value (the definition) will not be executed until the first time the value is accessed.

A related forth coming topic is the topic on lazy collections and projections and streams. They are all ways to lazily evaluate collections.

Note: The code for today must be put in a file and executed. Lazy val's cannot be demonstrated in the REPL because after each value is declared in a REPL the variable is accessed and it is printed out in the next line. If I considered it important enough I could have defined a method in the REPL, put the code in the method and then called the method and demonstrated it and if you wish feel free to do that. But I recommend creating a file and running scala yourfile

  1. val normalVal = {
  2.   println("---->>>   Initializing normal val    <<<----");
  3.   "This is the normal val"
  4. }
  5. lazy val lazyVal = {
  6.   println("---->>>   Initializing lazy val   <<<----");
  7.   "This is the lazy val"
  8. }
  9. println ("\n\nno references have been made yet\n\n")
  10. println ("Accessing normal val : ")
  11. println(normalVal)
  12. println ("\n\nAccessing lazy val : ")
  13. println(lazyVal)
  14. println ("\n\nAccessing lazy val a second time, there should be no initialization now: ")
  15. println(lazyVal)


  1. Thank you!

    I love your Scala code examples!

  2. Just for the record, I assume the expected output would be:

    ---->>>   Initializing normal val    <<<----

    no references have been made yet

    Accessing normal val :
    This is the normal val

    Accessing lazy val :
    ---->>>   Initializing lazy val   <<<----
    This is the lazy val

    Accessing lazy val a second time, there should be no initialization now: 
    This is the lazy val

  3. This comment has been removed by the author.

  4. No It is not like static. It is more like the lazy init pattern in java you might do:

    private volatile String field;

    public String getField() {
    if (field == null) {
    synchronized (this) {
    if (field == null) {
    field = // initialize
    return field;

  5. This comment has been removed by the author.

  6. Jesse's example is correct in Java 5 and beyond, because of the volatile keyword. However, anyone thinking to implement lazy initialization should first read