Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 340
Jean-Philippe Pellet Avatar asked Apr 16 '11 07:04

Jean-Philippe Pellet


2 Answers

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.

like image 198
Peter Schmitz Avatar answered Oct 06 '22 01:10

Peter Schmitz


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
like image 21
akihiro4chawon Avatar answered Oct 06 '22 00:10

akihiro4chawon