assert
Throws an error when condition is false.
let hitPoints = 100
assert(hitPoints > 0) // condition holds: nothing happens
println("hitPoints =", hitPoints)Output:
hitPoints = 100Parameters
condition | any | checked with the same rules as if |
message | function|string | text for the error, or a function that returns it optional |
Return value
null when condition is true.
Errors
Throws assertion failed when condition is false and no message is given. Otherwise throws message itself, or the string that a function message returns.
Notes
message is read lazily: when it is a function, the function runs only after condition has already failed, and only then. A condition that holds never calls it, so building the message can be as expensive as it needs to be.
Example
try { assert(1 + 1 == 3, "math is broken") } catch (e) { println("assert(1+1==3, ...) throws:", e) }
// the message may be a function; it runs only when the assertion actually fails
local pings = 0
function build_message() { pings += 1; return "built on demand" }
assert(true, build_message)
println("pings =", pings) // still 0: condition held, message unused
try { assert(false, build_message) } catch (e) { println("assert(false, ...) throws:", e) }
println("pings =", pings) // now 1: message was built to form the errorOutput:
assert(1+1==3, ...) throws: math is broken
pings = 0
assert(false, ...) throws: built on demand
pings = 1See also
error | Writes its arguments to the error stream. |
| globals | module index |