0

Here is Scala code:

  class FullDescription(val description: String) 
  class Logger {
      val description = //?????

      def onAttach(description: String) = 
       description = new FullDescription(description)

      // val lazy description = onAttach(???) -- 

      // ops! we don't know its actual argument, 
      // besides we should be able to make 
      // val description be evaluated from onAttach(...) and not vise versa
    }

It's given that for any class Logger it's guaranteed the method onAttach will be called only once. But it's unknown when the method onAttach will be called.

Is it possible to remain val description immutable and how do I do that? A lazy evaluation or something else?

Alan Coromano
  • 24,958
  • 53
  • 135
  • 205
  • 4
    I don't think it would be any different from http://stackoverflow.com/questions/17161401/initializing-a-val-lately situation – om-nom-nom Jun 18 '13 at 17:28
  • It's never guaranteed that your method will only be called once as far as the compiler is concerned, neither is it guaranteed that you won't try to access `description` before calling `onAttach`. – Jean-Philippe Pellet Jun 18 '13 at 19:16
  • You can pretty well ensure 0 or one invocations of a method if it's `private` and used in exactly one place in the source code to initialize a `lazy val`. – Randall Schulz Jun 18 '13 at 19:26
  • @RandallSchulz I didn't get it. – Alan Coromano Jun 19 '13 at 01:22

0 Answers0