Skip to main content

Conditionals

A conditional expression must evaluate to Bool. Most types can be typecast to Bool by using Bool(x) typecast, classes may define __bool__ method to participate in boolean contexts.

Evaluating Boolean Expressions

Boolean expressions come in many forms in Coco, such as

  • A comparison expression with valid comparison operators like <, >, ==, <= or >=.
  • An inversion with the ! operator.
  • A class that implements the __bool__ special method can be used directly or converted with Bool(x).
coco BoolClass

class Person:
field name String
field age U64

method __bool__(self) -> (result Bool):
yield result self.age > 18

endpoint local IsAdult(person Person) -> (ok Bool):
yield ok Bool(person)

endpoint local IsUnderage(person Person) -> (ok Bool):
yield ok !person

If/Else Conditionals

coco Conditionals

endpoint invoke DoIf(confirm Bool) -> (out String):
if !confirm:
out = "not yet"
else:
out = "done"

endpoint invoke DoIfLarge(number U64) -> (out String):
if number > 5000:
return (out: "done")
else if number >= 2500:
return (out: "almost")
else:
return (out: "not yet")

Conditionals in Coco begin with the if statement which can be used for optional execution of a block if the condition is met. The conditional expression must evaluate to a boolean as specified above. Alternate paths to the condition matching can be specified with the else and else if keywords

Ternary Operator

coco ternary

endpoint invoke Basic(v U64) -> (out U64):
out = (v if v < 10 else v * 10)

Syntax: result = (*true_value* if *condition* else *false_value)* Can have nested expression in true val and false val.

Switch-style Branching

endpoint DemoSwitch(x U64) -> (s String):
memory original = x
switch x * 2 :
case 0: s = "zero"
case 1, 2, 3:
s = "not too big"
case 24:
s = "twenty-four"
case x > 10 && x < 20:
s = "more than 10"
default:
s = "a lot"

switch statement can have multiple case elements and one optional default element. The value of expression can be of any type and the cases should either match the expression's type or be a boolean expressions.