Skip to content

Instantly share code, notes, and snippets.

@trylks
Created October 28, 2014 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trylks/5367b7c839395ce35f0f to your computer and use it in GitHub Desktop.
Save trylks/5367b7c839395ce35f0f to your computer and use it in GitHub Desktop.
Introducing the concept of eager laziness in a rudimentary way
package main
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import java.util.Calendar
object LazyEagerValues {
def toFuture[A, B](f: A => B): A => Future[B] = x => future { f(x) }
def main(args: Array[String]): Unit = {
traceThis("Starting")
val is_normal = expensiveComputation(1)
traceThis("is_normal 'done'")
lazy val is_lazy = expensiveComputation(1)
traceThis("is_lazy 'done'")
val eager_lazy_aux = toFuture(expensiveComputation)(1)
lazy val eager_lazy = Await.result(eager_lazy_aux, Duration.Inf)
traceThis("eager lazy 'done'")
traceThis(s"is normal: $is_normal")
traceThis(s"is_lazy: $is_lazy")
traceThis(s"eager_lazy: $eager_lazy")
}
def expensiveComputation(n: Int): Int = {
Thread sleep 10000
n + 1
}
// about laziness, no logger library, is there any by default in the language?
def traceThis(s: String) = {
println(s"${Calendar.getInstance().getTime()}: $s")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment