Booleans

In Toit, the boolean type is bool and its two values are written true and false.

Whenever built-in constructs need to evaluate a condition (for example in an if or a while), then Toit first "boolifies" the given value. The values false and null are treated like false and every other value is converted to true. So in a condition context, null is falsy and other non-booleans are truthy.

main:
  t := true
  if t:
    print "This is printed because t boolifies to true."
  f := false
  if f:
    // 'f' boolifies to false.
    unreachable
  n := null
  if n:
    // null in a condition boolifies to false.
    unreachable
  str := ""
  if str:
    // Strings, like every non-false non-null, object
    // boolify to true.
    print "This branch is executed."
  z := 0
  if z:
    // As before: 0, neither being false, nor being null, is
    // boolified to true.
    print "This branch is executed"
  list := []
  if list:
    print "This branch is reached"

  // Boolification only occurs in `if`, `for`, and `while`
  // conditions, and the first operand of the ternary `?:`
  // operator:
  b1 /bool := null // Error: null is not a bool!
  b2 /bool := s    // Error: A string is not a bool!
  b3 /bool := z    // Error: A number is not a bool!
  b4 /bool := list // Error: A list is not a bool!
  print (list ? "foo" : "bar")  // Prints "foo", because lists are truthy.
  print (null ? "foo" : "bar")  // Prints "bar", because null is falsy.
  print (0 ? "foo" : "bar")     // Prints "foo", because zero is truthy.