If...Else
Also known as: if else elif else if conditional ternary branch condition
● Beginner4 minBefore this: Operators, BooleansSpec 4.1
if runs a block only when its condition is true; else gives the other way.
Syntax
if condition {
// when condition is true
} else {
// otherwise
}Example
fn main() {
const stock = 3
if stock == 0 {
print("Sold out")
} else if stock < 5 {
print("Only {stock} left")
} else {
print("In stock")
}
}The program ran and printed:
kavach run else-if.kav
Only 3 leftThe conditions are tried top to bottom, and only the first true one runs its block.
The condition must be a Bool. if stock is an error; write what you mean, such as if stock > 0.
= is not ==
= sets a variable, and only as a statement of its own. In a condition it is an error that says what to write instead. The same holds for while:
fn main() {
const stock = 4
if stock = 4 {
print("four left")
}
}The compiler refused the program:
kavach run equals.kav
error: `=` sets a variable: to compare, write `==` (spec 4.1)A branch that can never run
Conditions are tried in order, so a wider one first hides a narrower one after it. The compiler warns:
fn grade(score: Int) -> String {
if score > 10 {
"good"
} else if score > 50 {
"great"
} else {
"keep going"
}
}
fn main() {
print(grade(70))
}The compiler warned, then the program ran:
kavach run never-true.kav
warning: this condition is never true here: `score > 50` means `score > 10`, and that branch is taken above. Check the order of the conditions (spec 4.7)good
In the editor, the quick fix "Remove this branch" takes out the else if and its block. An else after it stays, joined to the branch before.
One page for each form
Try it yourself
n, print whether it is even or odd.Show the answer
fn main() {
const n = 7
if n % 2 == 0 {
print("{n} is even")
} else {
print("{n} is odd")
}
}The program ran and printed:
kavach run even-odd.kav
7 is oddWhat Kavach does for you
No truthiness
A condition must be a
Bool.if countis an error, so0,""andnonecan never be taken for false by accident.
Check yourself
const stock = 0
if stock == 0 {
print("Sold out")
} else if stock < 5 {
print("Few left")
} else {
print("In stock")
}