Declaration
Functions in THP have a different syntax than PHP.
Function names must begin with a lowercase letter.
Minimal function
The following code shows a function without parameters and without return type:
fun say_hello() {
print("Hello")
}
say_hello()
thp
Functions are called the same way as in PHP.
With return type
If your function return any value, annotating the return
type is mandatory, and it’s done by placing an
arrow ->
followed by the return datatype:
fun get_random_number() -> Int {
return Random::get(0, 35_222)
}
val number = get_random_number()
thp
It’s an error to return from a function that doesn’t declare a return type:
fun get_random_number() {
// Error: the function does not define a return type
return Random::get(0, 35_222)
}
thp
You can omit the return
keyword if it’s placed on the last
expression on the function:
fun get_random_number() -> Int {
// The last expression of a function is
// automatically returned
Random::get(0, 35_222)
}
thp
Function parameters
Parameters are declared like C-style languages:
Type name
, separated by commas.
fun add(Int a, Int b) -> Int {
return a + b
}
val result = add(322, 644)
thp
THP has different semantics on parameters concerning pass by value, pass by reference and copy on write. This is detailed in another chapter.
Generic types
Functions can declare generic types by using the syntax
[Type]
.
The following example declares a generic T
and uses it
in the parameters and return type:
fun get_first_item[T](Array[T] array) -> T {
array[0]
}
val first = get_first_item[Int](numbers)
// The type annotation is optional if the compiler can infer the type
val first = get_first_item(numbers)
thp
Default arguments
TBD
Variadic arguments
TBD
Signature
() -> ()
() -> (Int)
(Int, Int) -> (Int)
[T](Array[T]) -> (T)
thp
Named arguments
fun html_special_chars(
String input,
Int? flags,
String? encoding,
Bool? double_encoding,
) -> String {
// ...
}
html_special_chars(input, double_encoding: false)
thp
TBD: If & how named arguments affect the order of the parameters
Named arguments with different names
fun greet(
String name,
String from: city,
) {
print("Hello {name} from {city}!")
}
greet("John", from: "LA")
thp