Created
October 1, 2015 18:33
-
-
Save andrewconner/55e4a1d0bd648db661c1 to your computer and use it in GitHub Desktop.
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
final class Lazily[A](f: () => A) { | |
private[this] var thunk: () => A = f | |
@volatile private var inst = false | |
private lazy val value: A = { | |
val r = thunk() | |
thunk = null // scalastyle:off | |
inst = true | |
r | |
} | |
def get: A = value | |
def isDefined = inst | |
def isEmpty = !inst | |
def nonEmpty = inst | |
def map[B](g: => A => B): Lazily[B] = Lazily(g(get)) | |
def foreach(f: A => Unit): Unit = { | |
if (isDefined) f(get) | |
else () | |
} | |
def flatMap[B](b: => A => Lazily[B]): Lazily[B] = b(get) | |
} | |
object Lazily { | |
def apply[T](f: => T) = new Lazily(() => f) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment