thp-lang.org/md/learn/functions/declaration.md

100 lines
1.2 KiB
Markdown
Raw Normal View History

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)
}
val number = get_random_number()
```
## With parameters and return type
```thp
fun get_secure_random_number(Int min, Int max) -> Int
{
Random::get_secure(min, max)
}
val number = get_secure_random_number(0, 65535)
```
## Generic types
```thp
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)
```
## 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
{
// ...
}
html_special_chars(input, double_encode: false)
```
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
fun replace(
String in: input,
String each: pattern,
String with: replacement,
) -> String
{
// Use input, pattern and replacement
}
replace(each: " ", in: "my name", with: "-")
```
2023-10-02 01:41:38 +00:00