Skip to content

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:
    print "This is not printed because f boolifies to false."
  n := null
  if n:
    print "This is not printed because n is null, and null boolifies to false."
  s/string? := ""
  if s:
    print "This is printed because s is a non-null string object, and like all objects it boolifies to true."
  z/num? := 0
  if z:
    print "This is printed because z is a non-null number, and like all objects it boolifies to true."
  l/List? := []
  if l:
    print "This is printed because l is a non-null list, and like all objects it boolifies to true."

  // Boolification only occurs in `if`, `for`, and `while` conditions.
  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 := l     // Error: A list is not a bool!