1

I found a question about DynamicVariable:

When we should use scala.util.DynamicVariable?

Then I tried to make an example to use the DynamicVariable

object m {

  class W {
    def wrapper[T](f: => T) = W.dyn.withValue("Bye")(f)
  }

  object W {
    private val dyn = new DynamicVariable[String]("Hello")
  }

  def main() = {
    val w = new W()
    w.wrapper {
      println(1)
    }
  }
 }
m.main()

It compiles successfully, but I have no ideas about how to extract the value assigned by the DynamicVariable, does anyone have ideas about this?

Community
  • 1
  • 1
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237

1 Answers1

1

This is a minimal snippet:

val dyn = new DynamicVariable[String]("withoutValue")
def print=println(dyn.value)
print
dyn.withValue("withValue") {
  print
}
print

The output will be:

withoutValue
withValue
withoutValue
Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237