`def` vs `val` vs `lazy val` evaluation in Scala
Solution 1:
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
Solution 2:
Yes, though for the 3rd one I would say "when that statement is executed", because, for example:
def foo() {
new {
val a: Any = sys.error("b is " + b)
val b: Any = sys.error("a is " + a)
}
}
This gives "b is null"
. b
is never evaluated and its error is never thrown. But it is in scope as soon as control enters the block.
Solution 3:
I would like to explain the differences through the example that i executed in REPL.I believe this simple example is easier to grasp and explains the conceptual differences.
Here,I am creating a val result1, a lazy val result2 and a def result3 each of which has a type String.
A). val
scala> val result1 = {println("hello val"); "returns val"}
hello val
result1: String = returns val
Here, println is executed because the value of result1 has been computed here. So, now result1 will always refer to its value i.e "returns val".
scala> result1
res0: String = returns val
So, now, you can see that result1 now refers to its value. Note that, the println statement is not executed here because the value for result1 has already been computed when it was executed for the first time. So, now onwards, result1 will always return the same value and println statement will never be executed again because the computation for getting the value of result1 has already been performed.
B). lazy val
scala> lazy val result2 = {println("hello lazy val"); "returns lazy val"}
result2: String = <lazy>
As we can see here, the println statement is not executed here and neither the value has been computed. This is the nature of lazyness.
Now, when i refer to the result2 for the first time, println statement will be executed and value will be computed and assigned.
scala> result2
hello lazy val
res1: String = returns lazy val
Now, when i refer to result2 again, this time around, we will only see the value it holds and the println statement wont be executed. From now on, result2 will simply behave like a val and return its cached value all the time.
scala> result2
res2: String = returns lazy val
C). def
In case of def, the result will have to be computed everytime result3 is called. This is also the main reason that we define methods as def in scala because methods has to compute and return a value everytime it is called inside the program.
scala> def result3 = {println("hello def"); "returns def"}
result3: String
scala> result3
hello def
res3: String = returns def
scala> result3
hello def
res4: String = returns def
Solution 4:
One good reason for choosing def
over val
, especially in abstract classes (or in traits that are used to mimic Java's interfaces), is, that you can override a def
with a val
in subclasses, but not the other way round.
Regarding lazy
, there are two things I can see that one should have in mind. The first is that lazy
introduces some runtime overhead, but I guess that you would need to benchmark your specific situation to find out whether this actually has a significant impact on the runtime performance. The other problem with lazy
is that it possibly delays raising an exception, which might make it harder to reason about your program, because the exception is not thrown upfront but only on first use.