Try Install Learn Blog API Packages GitHub
Pages

if...else

The if...else conditional expression returns one of two values based on a condition. It looks like this:

if condition {
  value1
} else {
  value2
}

There are some rules that will be enforced:

  • The condition must evaluate to type Bool
  • The values of both branches must evaluate to the same type
  • The else branch must be present, if it's missing you will get a syntax error, this ensures you handle all possibilities.

Currently there is no shorthand for a conditional expression.

else if ...

Multiple if...else statements can be written in sequence:

if number > 5 {
  true
} else if number > 2 {
  true
} else {
  false
}

Omitting else

The else branch can be omitted in two cases.

  • in any HTML element
  • in style tags

This example shows both cases:

component Main {
  state clicked : Bool = false

  style base {
    color: blue;

    if clicked {
      color: red;
    }
  }

  fun handleClick : Promise(Void) {
    next { clicked: true }
  }

  fun render : Html {
    <div::base>
      <div onClick={handleClick}>
        "Click me!"
      </div>

      if clicked {
        "I have been clicked!"
      }
    </div>
  }
}