Return to homepage

DOSATO

Copyright © 2024 Sebastiaan Heins

1.10 Switch

switch

switch is a master keyword, it is used to create a switch statement.
A switch statement is used to compare a value to a list of possible values.
If the value matches one of the possible values, the code block is executed.
If no value matches, the `other` block is executed.
Example of a switch statement:

make int a = 1
switch a => { // value to compare
    1 => { // case 1
        do say ("a is 1")
        break // exit switch
    }
    2 => {
        do say ("a is 2")
        break
    }
    other => { // default case
        do say ("a is not 1 or 2")
        break
    }
}

You can compare for any type of value, not just integers.
It's the same comparison as with a `==`.
You can also have multiple cases for the same block of code.

make string a = "hello"
switch a => {
    "hello", "HELLO" => { // multiple cases
        do say ("a is hello")
        break
    }
    "world" => {
        do say ("a is world")
        break
    }
    other => {
        do say ("a is not hello or world")
        break
    }
}

You can also fall through cases by not using a `break`.

make int a = 1
switch a => {
    1 => {
        do say ("a is 1")
        // no break, fall through to next case
    }
    2 => {
        do say ("a is 2 or 1")
        break // exit switch
    }
    other => {
        do say ("a is not 1 or 2")
        break
    }
}