Function parameters

Immutable reference


fun add_25(Array[Int] numbers) {
╰╴No statement matched
numbers.push(25) // Error: `numbers` is immutable }
thp

When using a regular type as a parameter, only it’s immutable properties can be used


fun count(Array[Int] numbers) -> Int {
╰╴No statement matched
val items_count = numbers.size() // Ok, `size` is pure items_count }
thp

To use immutable properties you must use a mutable reference.

Mutable reference


fun push_25(mut Array[Int] numbers) {
╰╴No statement matched
numbers.push(25) // Ok, will also mutate the original array }
thp

Placing a mut before the type makes the parameter a mutable reference. Mutable methods can be used, and the original data can be mutated.

The caller must define the value as var, and when calling must use mut.


var numbers = Array(0, 1, 2, 3)
              ╰╴Invalid variable declaration
push_25(mut numbers) // Pass `numbers` as reference. print(numbers(4)) // `Some(25)`
thp

Clone


fun add_25(clone Array[Int] numbers) {
╰╴No statement matched
numbers.push(25) // Ok, the original array is unaffected }
thp

Using the clone keyword before the type creates a mutable copy of the parameter (CoW). The original data will not be mutated.

The caller must also use clone when calling the function.


val numbers = Array(1, 2, 3, 4)
              ╰╴Invalid variable declaration
add_25(clone numbers) // Pass `numbers` as clone. print(numbers(4)) // None
thp