Search code examples
smalltalkoperator-precedence

Smalltalk - is there something similar to && from C?


I have to write a pure-object Smalltalk program, in which I need to evaluate conditions until one of them fails. I know that in C, we can use the && operator for this, and conditions only get evalutated if necessary.

Is there something similar in Smalltalk?


Solution

  • Conditional "anding" can be achieved by using the & message, or the and: message.

    firstBooleanExpression & secondBooleanExpression
        ifTrue: [ 'do something' ].
    

    Using & as show above, the second part of the condition (secondBooleanExpression) is evaluated regardless of whether the first half evaluates to true or false.

    (firstBooleanExpression and: [secondBooleanExpression])
        ifTrue: [ 'do something' ].
    

    Using and:, on the other hand, the second part is only evaluated if the first half evaluates to true. Typically you'd use this form, unless you explicitly wanted to evaluate the second half.

    The same principle applies to or:.