Skip to content

Instantly share code, notes, and snippets.

@daithiocrualaoich
Created February 17, 2011 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daithiocrualaoich/830846 to your computer and use it in GitHub Desktop.
Save daithiocrualaoich/830846 to your computer and use it in GitHub Desktop.
Lazy evaluation of closures during object construction
scala> def test = { println("Evaluating"); "test" }
test: java.lang.String
scala> case class TestClass(s: String) { override def toString = "overrided so the REPL doesn't coerse evaluation of s" }
defined class TestClass
scala> val t = TestClass(test)
Evaluating
t: TestClass = overrided so the REPL doesn't coerse evaluation of s
scala> // Construction of TestClass has evaluated s attribute
scala> trait TestTrait { def s: String }
defined trait TestTrait
scala> val t = new TestTrait { lazy val s = test }
t: java.lang.Object with TestTrait = $anon$1@4b3ca972
scala> // Construction of TestTrait instance has not evaluated s attribute
scala> t.s
Evaluating
res1: String = test
scala> t.s
res2: String = test
scala> // Second call for s attribute doesn't reevaluate
scala>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment