Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does scala have a lazy evaluating wrapper?

I want to return a wrapper/holder for a result that I want to compute only once and only if the result is actually used. Something like:

def getAnswer(question: Question): Lazy[Answer] = ???

println(getAnswer(q).value)

This should be pretty easy to implement using lazy val:

class Lazy[T](f: () => T) {
  private lazy val _result = Try(f())

  def value: T = _result.get
}

But I'm wondering if there's already something like this baked into the standard API.

A quick search pointed at Streams and DelayedLazyVal but neither is quite what I'm looking for.

Streams do memoize the stream elements, but it seems like the first element is computed at construction:

def compute(): Int = { println("computing"); 1 }

val s1 = compute() #:: Stream.empty
// computing is printed here, before doing s1.take(1)

In a similar vein, DelayedLazyVal starts computing upon construction, even requires an execution context:

val dlv = new DelayedLazyVal(() => 1, { println("started") })
// immediately prints out "started"
like image 809
Dilum Ranatunga Avatar asked Nov 21 '25 15:11

Dilum Ranatunga


1 Answers

There's scalaz.Need which I think you'd be able to use for this.

like image 164
Hugh Avatar answered Nov 23 '25 05:11

Hugh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!