thp-web/md/learn/functions/declaration.md

1.2 KiB

Declaration

No parameters, no return

fun say_hello()
{
    print("Hello")
}

say_hello()

With return type

fun get_random_number() -> Int
{
    Random::get(0, 35_222)
}

let number = get_random_number()

With parameters and return type

fun get_secure_random_number(Int min, Int max) -> Int
{
    Random::get_secure(min, max)
}

let number = get_secure_random_number(0, 65535)

Generic types

fun get_first_item[T](Array[T] array) -> T
{
    array.[0]
}

let first = get_first_item[Int](numbers)
// The type annotation is optional if the compiler can infer the type

let first = get_first_item(numbers)

Signature

() -> ()
() -> Int
(Int, Int) -> Int
[T](Array[T]) -> T

Named arguments

fun html_special_chars(
    String input,
    Int? flags,
    String? encoding,
    Bool? double_encoding,
) -> String
{
    // ...
}

html_special_chars(input, double_encode: false)

Named arguments with different names

fun replace(
    String in: input,
    String each: pattern,
    String with: replacement,
) -> String
{
    // Use input, pattern and replacement
}

replace(each: " ", in: "my name", with: "-")