title: Why does lazy val behave so mysteriously in enumeration, Scala?
body: <p>I want to find lazily the maximum of all defined enum value names. The following piece of code when executed falls into an endless loop printing repeatedly <code>InvocationTargetException</code>.</p>
  
  <pre><code>object Enum extends Enumeration with App {
    val A, B = new Val
    lazy val foo = values.maxBy(_.toString)
  
    println(Enum.foo)
  }
  </code></pre>
  
  <p>The problem does not appear when <code>foo</code> is a <code>def</code>.</p>
  
  <p>Why does it behave like this? Shouldn't <code>lazy val</code> be just a memorized <code>def</code>?</p>
  
  <p>Oddly, the following piece of code does work as expected:</p>
  
  <pre><code>object Enum extends Enumeration with App {
    val A, B = new Val
    lazy val foo = values.foldLeft(""){(a, b) =&gt; a + b}
  
    println(Enum.foo)
  }
  </code></pre>
  
  <p>I'm using scala 2.11.7.</p>
  
  <p>// --- Solution</p>
  
  <p>The problem is that foo is of <code>Value</code> type and thus is interpreted as an enum value. 
  A way around the problem is creating a proxy <code>def</code> to <code>lazy val</code> as in the following piece of code:</p>
  
  <pre><code>object Enum extends Enumeration with App {
    val A, B = new Val
    private lazy val fooBuffer = values.maxBy(_.toString)
    def foo = fooBuffer
  
    println(Enum.foo)
  }
  </code></pre>