Search code examples
smalltalk

Smalltalk lazy initialization as method call?


Having a small problem here with a variable not initializing. Are these equivalent?

comments
        ^ comments ifNil: [ comments := OrderedCollection new ]

--

comments
        ^ comments ifNil: [ self initializeComments ]

initializeComments
    comments := OrderedCollection new

Solution

  • One has to return the comments variable in the initializeComments method, otherwise the comments getter method will return self for the second variant in case of an uninitialized variable.

    I don't want to return anything in initializeComments so I used:

    comments
        ^ comments ifNil: [ self initializeComments. comments ]
    

    Or:

    comments
        comments ifNil: [ self initializeComments ]. 
        ^ comments
    

    
Thanks Mike!

    PS. For a more detailed explanation see @LeandroCaniglia answer below.