8.12

1.8 Variables and Values🔗ℹ

Variables are immutable unless they are declared with the mutable binding operator. The := infix operator assigns to a mutable variable.

def mutable todays_weather = "sunny"

> todays_weather

"sunny"

> todays_weather := "rainy"

> todays_weather

"rainy"

fun f(mutable x):

  x := x + 8

  x

> f(10)

18

> f := 5

:=: left-hand argument is not a mutable identifier

The := operator can also change object fields accessed via . when a class field is declared mutable.

class Box(mutable content)

> def present = Box("socks")

> present.content

"socks"

> present.content := "toy"

> present.content

"toy"

Most expressions in Rhombus produce a single value. The values form, however, returns multiple values:

> values(1, "apple")

1

"apple"

When an expression in a module body returns multiple values, each one is printed. Returning multiple values is different that returning one value that is a list of values, similar to the way that passing multiple arguments to a function is different than passing one argument that is a list. To receive multiple values from an expression, you need to use a special binding form.

When the def binding form is followed by parentheses with n groups, then the right-hand side should produce n values, and each value is matched against the corresponding group.

def (n, s) = values(1, "apple")

> n

1

> s

"apple"

A definition binding with def or let can also use values in the outermost pattern, and that’s the same as not writing values, but it makes the receiver and sender side look more the same:

def values(n, s) = values(1, "apple")

> n

1

> s

"apple"