Search code examples
smalltalk

Visibilily in #inject:into: block


This code:

((1 to: 10)
    inject: (WriteStream on: String new)
    into: [ :strm :each |
        ((each rem: 3) = 0)
            ifTrue: [
                strm
                    nextPutAll: each printString;
                    space;
                    yourself ]]) contents

fails because strm is undefined where it is used in the ifTrue: block. Why is it not visible there?

Edit: I tried it out in VASt and Pharo.


Solution

  • The problem is that the implied ifFalse: branch returns nil. To fix this, try the following:

    ((1 to: 10)
        inject: (WriteStream on: String new)
        into: [ :strm :each |
            ((each rem: 3) = 0)
                ifFalse: [strm]  "This is needed to avoid nil being returned"
                ifTrue: [
                    strm
                        nextPutAll: each printString;
                        space;
                        yourself ]]) contents