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
Examples:
- val normalVal = {
- println("---->>> Initializing normal val <<<----");
- "This is the normal val"
- }
- lazy val lazyVal = {
- println("---->>> Initializing lazy val <<<----");
- "This is the lazy val"
- }
- println ("\n\nno references have been made yet\n\n")
- println ("Accessing normal val : ")
- println(normalVal)
- println ("\n\nAccessing lazy val : ")
- println(lazyVal)
- println ("\n\nAccessing lazy val a second time, there should be no initialization now: ")
- println(lazyVal)
Thank you!
ReplyDeleteI love your Scala code examples!
Just for the record, I assume the expected output would be:
ReplyDelete---
---->>> 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
---
This comment has been removed by the author.
ReplyDeleteis it like static in java???
ReplyDeleteNo It is not like static. It is more like the lazy init pattern in java you might do:
ReplyDeleteprivate volatile String field;
public String getField() {
if (field == null) {
synchronized (this) {
if (field == null) {
field = // initialize
}
}
return field;
}
This comment has been removed by the author.
ReplyDeleteJesse's example is correct in Java 5 and beyond, because of the volatile keyword. However, anyone thinking to implement lazy initialization should first read http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
ReplyDelete