Control flow
If
Usual if is a ifTrue:
message for Boolean type, that takes codeblock as argument.
It will evaluate this block if it was send to true.
There is 4 messages with all possible combination.
The most common to use is ifTrue:ifFalse:
Try to say what numbers will be printed.
The last 2 messages have the signature: Boolean ifTrue: [ -> T] ifFalse: [ -> T] -> T
so they can be used as expressions
Which means that the last expression of each branch is returned as a result.
In the first example x will be equal 1:
In this theoretical program we are getting content of the config file if it exists or create it if not.
Notice: codeblocks always return its last expression as value
Match
There was no way to do this in original Smalltalk, so they used to create a table with match-values to codeblocks
But since in niva I replaced inheritance with tagged unions I really need special syntax for matching.
You can see that else branch, is just a usual branch where condition is missing| 2 => x dec echo
| ??? => x echo
|=> x echo
Here example with unions, despite you will learn them a little bit later:
If syntax sugar
Since if is quite often thing, I created syntax sugar for ifTrue: true => expr
for true ifTrue: [expr]
andtrue => expr |=> expr
for true ifTrue: [expr] ifTrue: [expr]
You can find consistency between if and match.
| match againts => do
conditiont => do
If abuse
There are no if ifelse else syntax chain, but you can do it like with ? :
op in C
I've never been in a situation where it would be necessary, prefer simple ifs and matches, this is for some very corner cases.