Am I right understanding that
def
is evaluated every time it gets accessed
lazy val
is evaluated once it gets accessed
val
is evaluated once it gets into the execution scope?
Scala provides a nice language feature called lazy val that defers the initialization of a variable. The lazy initialization pattern is common in Java programs. Though it seems tempting, the concrete implementation of lazy val has some subtle issues.
Lazy Evaluation in ScalaHaskell is a functional programming language that uses lazy evaluation by default.
Lazy initialization means that whenever an object creation seems expensive, the lazy keyword can be stick before val. This gives it the advantage to get initialized in the first use i.e. the expression inbound is not evaluated immediately but once on the first access. Example: // Scala program of Lazy val.
def is the keyword you use to define a method, the method name is double , and the input parameter a has the type Int , which is Scala's integer data type. The body of the function is shown on the right side, and in this example it simply doubles the value of the input parameter a : def double(a: Int) = a * 2 -----
Yes, but there is one nice trick: if you have lazy value, and during first time evaluation it will get an exception, next time you'll try to access it will try to re-evaluate itself.
Here is example:
scala> import io.Source import io.Source scala> class Test { | lazy val foo = Source.fromFile("./bar.txt").getLines | } defined class Test scala> val baz = new Test baz: Test = Test@ea5d87 //right now there is no bar.txt scala> baz.foo java.io.FileNotFoundException: ./bar.txt (No such file or directory) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:137) ... // now I've created empty file named bar.txt // class instance is the same scala> baz.foo res2: Iterator[String] = empty iterator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With