Skip to content

Commit 3d1cec8

Browse files
authored
Merge pull request #33 from chaitanyawaikar/task/SCALA-28-lazy_val_deep_dive
Diving Deep into Lazy Vals
2 parents 3873bb9 + 36f9140 commit 3d1cec8

File tree

2 files changed

+105
-0
lines changed

2 files changed

+105
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.baeldung.scala
2+
3+
import scala.concurrent.ExecutionContext.Implicits.global
4+
import scala.concurrent._
5+
import scala.concurrent.duration._
6+
7+
class LazyVal {
8+
9+
var age = 27
10+
11+
lazy val getMemberNo = {
12+
age = age + 1
13+
8
14+
}
15+
}
16+
17+
object FirstObj {
18+
lazy val initialState = 42
19+
lazy val start = SecondObj.initialState
20+
}
21+
22+
object SecondObj {
23+
lazy val initialState = FirstObj.initialState
24+
}
25+
26+
object Deadlock extends App {
27+
def run = {
28+
val result = Future.sequence(Seq(
29+
Future {
30+
FirstObj.start
31+
},
32+
Future {
33+
SecondObj.initialState
34+
}))
35+
Await.result(result, 10.second)
36+
}
37+
38+
run
39+
}
40+
41+
object LazyValStore {
42+
43+
lazy val squareOf5 = square(5)
44+
lazy val squareOf6 = square(6)
45+
46+
def square(n: Int): Int = n * n
47+
}
48+
49+
object SequentialLazyVals extends App {
50+
def run = {
51+
val futures = Future.sequence(Seq(
52+
Future {
53+
LazyValStore.squareOf5
54+
},
55+
Future {
56+
LazyValStore.squareOf6
57+
}))
58+
Await.result(futures, 5.second)
59+
}
60+
61+
run.foreach(println)
62+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.baeldung.scala
2+
3+
import org.scalatest.FunSuite
4+
import org.scalatest.Matchers._
5+
6+
import scala.concurrent.ExecutionContext.Implicits.global
7+
import scala.concurrent.duration._
8+
import scala.concurrent.{Future, _}
9+
import com.baeldung.scala
10+
11+
class LazyValUnitTest extends FunSuite {
12+
13+
test("lazy val is computed only once") {
14+
//given
15+
val lazyVal = new LazyVal
16+
lazyVal.getMemberNo //initialize the lazy val
17+
lazyVal.age shouldBe 28
18+
19+
//when
20+
lazyVal.getMemberNo
21+
22+
//then
23+
lazyVal.age shouldBe 28
24+
}
25+
26+
test("lazy vals should execute sequentially in an instance ") {
27+
//given
28+
val futures = Future.sequence(Seq(
29+
Future {
30+
scala.LazyValStore.squareOf5
31+
},
32+
Future {
33+
scala.LazyValStore.squareOf6
34+
}))
35+
36+
//when
37+
val result = Await.result(futures, 5.second)
38+
39+
//then
40+
result should contain(25)
41+
result should contain(36)
42+
}
43+
}

0 commit comments

Comments
 (0)