When trying to delete the first object, how can I catch the empty LinkedList exception in Smalltalk?

I am new to Smalltalk and try not to use if statements! In Python, I would write:

try:
   element = LinkedList.remove()
except:
   element = "nil"
finally:
   return element

What is the equivalent in Smalltalk?

+4
source share
2 answers

Short answer:

^aLinkedList remove: aLinkOrObject ifAbsent: [nil]

Note that in Smalltalk, all collections that support item deletion also support the message remove:ifAbsent:. The first argument is the item to delete, and the second is the block that would handle the case when the item is not in the collection.

More generally, the way Smalltalk handles exceptions follows a pattern:

[<Smalltalk expression>] on: Error do: [:ex | <handle ex>]

Error Exception, , .

- Smalltalk, , Smalltalk.

@SeanDeNigris , , , : ? , remove:ifAbsent:, , . , .

:

^aLinkedList remove: aLinkedList first ifAbsent: [nil]

, aLinkedList first , . , ifAbsent: . , , . , , :

^aLinkedList isEmpty
    ifTrue: [nil]
    ifFalse: [aLinkedList remove: aLinkedList first]

:

^[aLinkedList remove: aLinkedList first] on: Error do: [nil]

, . . ? , . - , . . , , , , , . on:do: , .

+7

, , #on:do:

... - , ""! Python , , , Smalltalk - #removeFirstUnlessEmpty ( , ). , , , if.

, Smalltalk #ifTrue: , , ... , ; )

+3

All Articles