Skip to content

Diving Deep into Lazy Vals #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions core-scala/src/main/scala/com/baeldung/scala/LazyVal.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package com.baeldung.scala

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._

class LazyVal {

var age = 27

lazy val getMemberNo = {
age = age + 1
8
}
}

object FirstObj {
lazy val initialState = 42
lazy val start = SecondObj.initialState
}

object SecondObj {
lazy val initialState = FirstObj.initialState
}

object Deadlock extends App {
def run = {
val result = Future.sequence(Seq(
Future {
FirstObj.start
},
Future {
SecondObj.initialState
}))
Await.result(result, 10.second)
}

run
}

object LazyValStore {

lazy val squareOf5 = square(5)
lazy val squareOf6 = square(6)

def square(n: Int): Int = n * n
}

object SequentialLazyVals extends App {
def run = {
val futures = Future.sequence(Seq(
Future {
LazyValStore.squareOf5
},
Future {
LazyValStore.squareOf6
}))
Await.result(futures, 5.second)
}

run.foreach(println)
}
43 changes: 43 additions & 0 deletions core-scala/src/test/scala/com/baeldung/scala/LazyValUnitTest.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.baeldung.scala

import org.scalatest.FunSuite
import org.scalatest.Matchers._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Future, _}
import com.baeldung.scala

class LazyValUnitTest extends FunSuite {

test("lazy val is computed only once") {
//given
val lazyVal = new LazyVal
lazyVal.getMemberNo //initialize the lazy val
lazyVal.age shouldBe 28

//when
lazyVal.getMemberNo

//then
lazyVal.age shouldBe 28
}

test("lazy vals should execute sequentially in an instance ") {
//given
val futures = Future.sequence(Seq(
Future {
scala.LazyValStore.squareOf5
},
Future {
scala.LazyValStore.squareOf6
}))

//when
val result = Await.result(futures, 5.second)

//then
result should contain(25)
result should contain(36)
}
}