Scala:Lazy
lazy val
변수를 사용할 때 평가하며 해당 내용을 캐싱한다.
Example
아래의 세 가지 방법을 출력 및 비교해 보면 된다.
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!")
}
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.")
}
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.")
}