有感於自己Scala的根基不是很紮實, 於是開始看一些Scala G+群組推薦的文章,
希望能把code寫的更好一些.
今天看的是
Design Patterns in Scala其中提到了lazy的運用, 重新溫習了一下就順便做筆記囉!
一般的val是在定義的時候, 就會馬上執行而得到值.
加了lazy, 顧名思義就是會變懶惰XD
要等到它首次被存取的時候才會被執行而得到值.
用console可以簡單看出差異
scala> lazy val y = {println("i'm y"); "y"}
y: java.lang.String = <lazy>
scala> y
i'm y
res22: java.lang.String = y
scala> y
res23: java.lang.String = y
scala> val x = { println("i'm x"); "x"}
i'm x
x: java.lang.String = x
scala> x
res24: java.lang.String = x
欸, 那lazy val跟def是不是感覺有點像勒!!??
lazy val是首次被存取的時候才會被執行, 但也只會被執行一次.
下面Date的例子就可以明顯看出差異啦!
scala> lazy val foo = new java.util.Date
foo: java.util.Date =
scala> foo
res13: java.util.Date = Mon Jan 27 17:48:35 CST 2014
scala> foo
res14: java.util.Date = Mon Jan 27 17:48:35 CST 2014
scala> def foo = new java.util.Date
foo: java.util.Date
scala> foo
res16: java.util.Date = Mon Jan 27 17:48:54 CST 2014
scala> foo
res17: java.util.Date = Mon Jan 27 17:48:57 CST 2014
ref:
- What does a lazy val do?
advanced:
- What's the (hidden) cost of Scala's lazy val?
-
if the initialization of a lazy val throws an exception, it will attempt to reinitialize the val at next access.
No comments:
Post a Comment