Created
October 28, 2014 18:15
-
-
Save trylks/5367b7c839395ce35f0f to your computer and use it in GitHub Desktop.
Introducing the concept of eager laziness in a rudimentary way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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