Created
          February 17, 2011 02:43 
        
      - 
      
- 
        Save daithiocrualaoich/830846 to your computer and use it in GitHub Desktop. 
    Lazy evaluation of closures during object construction
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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