LEVIATHAN v962456e · 962456eee1

Standard Library

class bool

The boolean type: a value is either true or false.

since 0.1.0-alpha.1linuxwindowswasm

Overview

bool is a value type stored unboxed. Comparison operators such as == and < produce a bool, &&, || and ! combine them, and if, while and the conditional operator ?: consume one. A bool has no arithmetic and does not convert to or from int.

Description

bool has two values, true and false, written as the keywords of the same names. A bool is a value type and defaults to false.

Comparisons (==, !=, <, <=, >, >=) produce a bool. The operators &&, || and ! combine them. && and || are short-circuiting: the right operand is evaluated only when the left one does not already decide the result.

Logical operators and short-circuiting

int calls = 0;
bool probe(bool v) {
    calls = calls + 1;
    return v;
}
bool a = true;
bool b = false;
console.writeln(a && b);
console.writeln(a || b);
console.writeln(!a);
console.writeln(a == !b);
console.writeln(false && probe(true));
console.writeln(true || probe(true));
console.writeln(calls);
console.writeln(probe(false) || probe(true));
console.writeln(calls);
console.writeln(a.toString() + "!");
bool flag;
console.writeln(flag);
false
true
false
true
false
true
0
true
2
true!
false

Rules

  • A bool never converts to or from a number. bool x = 1; is a compile error, and so is x == 1 for a bool x.
  • ! accepts a bool only. !0 and !"text" are compile errors; write an explicit test such as n != 0 or !text.isEmpty().
  • && and || stop at the first operand that decides the result, so a call on the right of a short-circuited operator does not run.
  • toString() returns "true" or "false".

Examples

Booleans from comparisons:

Comparisons produce bool

int n = 5;
bool small = n < 10;
bool even = n % 2 == 0;
console.writeln(small);
console.writeln(even);
console.writeln(small && !even);
true
false
true

Notes

bool has a single method, toString().

Examples

Comparisons and logic

int a = 7;
int b = 2;
bool big = a > 5 && b < 5;
console.writeln(big);
console.writeln(!big);
console.writeln("big is " + big.toString());
console.writeln("interpolated: ${big}");
true
false
big is true
interpolated: true

Methods

toString

toString() -> string

Convert the value to its text form.

Returns

"true" or "false".

Examples

bool ok = 3 < 4;
console.writeln(ok.toString());
console.writeln(false.toString());
console.writeln("ok is " + ok.toString());
true
false
ok is true

See also