Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`def` vs `val` vs `lazy val` evaluation in Scala

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?

like image 963
Ivan Avatar asked Feb 26 '12 00:02

Ivan


People also ask

What is lazy Val in Scala?

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.

Does Scala have lazy evaluation?

Lazy Evaluation in ScalaHaskell is a functional programming language that uses lazy evaluation by default.

What is lazy evaluation and lazy Val?

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.

What does def mean in Scala?

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 -----


1 Answers

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 
like image 150
om-nom-nom Avatar answered Sep 22 '22 20:09

om-nom-nom