If, in Scala, this val foo: Int = 0
gets decompiled to this:
private[this] val foo_: Int = 0
def foo: Int = foo_
Then how can def
s evaluate each time they are called but val
s are evaluated only once? Since the val
is decompiled to a def
anyway?
For a val
, there is a private variable ("val"), and a getter method ("def"). The variable is initialized with a value, which is computed once.
For a def
, there is no variable to "cache" the value, so it it is computed every time.
class Foo {
val bar = { println("BAR"); "bar" }
}
Is roughly equivalent to
class Foo {
private var bar_ = { println("BAR"); "bar" }
def bar = bar_
}
The block initializing bar_
is only executed once, when the instance of the class is being created. So, something like
val f = new Foo
println("Created")
f.bar
f.bar
f.bar
Will print out "BAR", then "Created", and nothing else.
But if you define Foo
as
class Foo {
def bar = { println("BAR"); "bar" }
}
Then the block is evaluated every time you access bar
, and the code above, will first print "Created", and then "BAR" three times.