Scala:Lazy
lastmod 2019-01-22created 2019-01-224 edits
lazy val
Evaluated when the variable is used, and the result is cached.
Example
- [Recommended] Value naming and expression evaluation in Scala
Print and compare the three approaches below.
Using val:
object Evaluation extends App {
val cooktimeInMin = {
println("Hi I'm cup noodle!")
4
}
println("Let's start cooking!")
println("Cup noodle takes " + cooktimeInMin + " min.")
println("Oh, " + cooktimeInMin + " min is soooo short!")
}
Using lazy val:
object Evaluation extends App {
lazy val cooktimeInMin = {
println("Hi I'm cup noodle!")
4
}
println("Let's start cooking!")
println("Cup noodle takes " + cooktimeInMin + " min.")
}
Using def:
object Evaluation extends App {
def cooktimeInMin = {
println("Hi I'm cup noodle!")
4
}
val secPerMin = 60
println("Let's start cooking!")
println("Cup noodle takes " + cooktimeInMin + " min.")
println("Or, it takes " + cooktimeInMin * secPerMin + " sec.")
}