2023-10-02 01:41:38 +00:00
|
|
|
# Declaration
|
|
|
|
|
|
|
|
|
|
|
|
## No parameters, no return
|
|
|
|
|
|
|
|
```thp
|
|
|
|
fun say_hello()
|
|
|
|
{
|
|
|
|
print("Hello")
|
|
|
|
}
|
|
|
|
|
|
|
|
say_hello()
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
## With return type
|
|
|
|
|
|
|
|
```thp
|
|
|
|
fun get_random_number() -> Int
|
|
|
|
{
|
|
|
|
Random::get(0, 35_222)
|
|
|
|
}
|
|
|
|
|
2024-02-20 10:17:21 +00:00
|
|
|
val number = get_random_number()
|
2023-10-02 01:41:38 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
## With parameters and return type
|
|
|
|
|
|
|
|
```thp
|
|
|
|
fun get_secure_random_number(Int min, Int max) -> Int
|
|
|
|
{
|
|
|
|
Random::get_secure(min, max)
|
|
|
|
}
|
|
|
|
|
2024-02-20 10:17:21 +00:00
|
|
|
val number = get_secure_random_number(0, 65535)
|
2023-10-02 01:41:38 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
## Generic types
|
|
|
|
|
|
|
|
```thp
|
|
|
|
fun get_first_item[T](Array[T] array) -> T
|
|
|
|
{
|
2024-01-01 14:11:41 +00:00
|
|
|
array[0]
|
2023-10-02 01:41:38 +00:00
|
|
|
}
|
|
|
|
|
2024-02-20 10:17:21 +00:00
|
|
|
val first = get_first_item[Int](numbers)
|
2023-10-02 01:41:38 +00:00
|
|
|
// The type annotation is optional if the compiler can infer the type
|
|
|
|
|
2024-02-20 10:17:21 +00:00
|
|
|
val first = get_first_item(numbers)
|
2023-10-02 01:41:38 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
## Signature
|
|
|
|
|
|
|
|
|
|
|
|
```thp
|
|
|
|
() -> ()
|
|
|
|
() -> Int
|
|
|
|
(Int, Int) -> Int
|
|
|
|
[T](Array[T]) -> T
|
|
|
|
```
|
|
|
|
|
|
|
|
|
2023-10-05 12:56:34 +00:00
|
|
|
## Named arguments
|
|
|
|
|
|
|
|
```thp
|
|
|
|
fun html_special_chars(
|
|
|
|
String input,
|
|
|
|
Int? flags,
|
|
|
|
String? encoding,
|
|
|
|
Bool? double_encoding,
|
|
|
|
) -> String
|
|
|
|
{
|
|
|
|
// ...
|
|
|
|
}
|
|
|
|
|
2024-01-01 14:11:41 +00:00
|
|
|
html_special_chars(input, double_encoding: false)
|
2023-10-05 12:56:34 +00:00
|
|
|
```
|
|
|
|
|
2024-01-01 14:11:41 +00:00
|
|
|
TBD: If & how named arguments affect the order of the parameters
|
|
|
|
|
2023-10-24 01:39:34 +00:00
|
|
|
## Named arguments with different names
|
2023-10-02 01:41:38 +00:00
|
|
|
|
2023-10-24 01:39:34 +00:00
|
|
|
```thp
|
2024-01-01 14:11:41 +00:00
|
|
|
fun greet(
|
|
|
|
String name,
|
|
|
|
String from: city,
|
|
|
|
)
|
2023-10-24 01:39:34 +00:00
|
|
|
{
|
2024-01-01 14:11:41 +00:00
|
|
|
print("Hello {name} from {city}!")
|
2023-10-24 01:39:34 +00:00
|
|
|
}
|
|
|
|
|
2024-02-20 10:53:38 +00:00
|
|
|
greet("John", from: "LA")
|
2023-10-24 01:39:34 +00:00
|
|
|
```
|
2023-10-02 01:41:38 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|