Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

Can I check whether a lazy val has been evaluated in Scala?

For instance, in a toString method, I would like to give info on whether a lazy val member of a class has been evaluated, and if so, print its value. Is this possible?

Upvotes: 16

Views: 2141

Answers (3)

George Pligoropoulos
George Pligoropoulos

Reputation: 2939

I have also found it useful to check if the lazy value is in fact evaluated in some tricky situations.
And this is a generic class you could use:

class ExtraLazy[T](notYetEvaluatedValue: => T) {
  var isSet = false;
  lazy val value: T = {
    Logger("lazy value being evaluated");
    isSet = true;
    notYetEvaluatedValue;
  }
}

Upvotes: 2

akihiro4chawon
akihiro4chawon

Reputation: 296

If you want direct access to the compiler generated field, please try the following code.

import java.lang.reflect._

class A {
  lazy val member = 42
  def isEvaluated = 
    (1 & getClass.getField("bitmap$0").get(this).asInstanceOf[Int]) == 1
}

val a = new A
println(a.isEvaluated) // => true
println(a.member)
println(a.isEvaluated) // => false

Upvotes: 9

Peter Schmitz
Peter Schmitz

Reputation: 5844

As far as I know, you can´t. But you can help with that:

  class A {
    var isMemberSet = false
    lazy val member = { isMemberSet = true; 8 }
  }

  val a = new A
  a.isMemberSet // false
  a.member // 8
  a.isMemberSet // true

Of course, visibility and access modifier have to be adapted.

Upvotes: 15

Related Questions