Block Comparison in Squeak Smalltalk

I program in a script and you need to compare two blocks of code as follows: (toRunBlock is an instance variable)

~~~Other code~~~
toRunBlock := [nil].
~~~Other code~~~

But at some point I need to compare it with another block of code:

(toRunBlock = [nil]) ifTrue: [
    "Run some code if toRunBlock hasn't been overwritten"
].

But this check always gives false, and I cannot find a way to check if they are equal. Can someone help me with this?

+4
source share
2 answers

As @LeandroCaniglia pointed out, you do not need to compare blocks. Here are two ways to solve your problem without comparing the blocks:

 
  • initialize the variable nil. In your accessor method, you initialize it lazily:

    toRunBlock
        ^ toRunBlock ifNil: [ [] ]
    

    , toRunBlock, nil, #toRunBlock , .

    :

    toRunBlock ifNil: [
        "Run some code if toRunBlock hasn't been overwritten"
    ].
    
  • , , . setter, :

    toRunBlock: aBlock
        toRunBlock := aBlock.
        hasToRunBlockBeenSet := true
    

    , :

    hasToRunBlockBeenSet
        ^ hasToRunBlockBeenSet ifNil: [ false ]
    

    :

    self hasToRunBlockBeenSet ifTrue: [
        "Run some code if toRunBlock hasn't been overwritten"
    ].
    

, , .

+6

BlockClosures, . , , , . ( ), , [nil] .

, , , . , [nil] , [nil] (, defaultRunBlock) RunBlock ( ) , , toRunBlock .

Object subclass: #YourClass
    instanceVariableNames: 'toRunBlock defaultRunBlock' 
        "or as class variable:"
    classVariableNames: 'DefaultRunBlock'
    poolDictionaries: ''
    category: 'Kernel-Methods'

initialize
    defaultRunBlock := [nil]

otherCode
    toRunBlock := defaultRunBlock

whereYouCompareThem
    toRunBlock == defaultRunBlock ifTrue: [ "..." ]

, toRunBlock , .

whereYouCompareThem
    toRunBlock == previousRunBlock ifTrue: [ "..." ].
    previousRunBlock := toRunBlock
+3

All Articles