2023-09-15 03:15:35 +00:00
|
|
|
# Variables
|
|
|
|
|
2023-10-02 01:41:38 +00:00
|
|
|
thp distinguishes between mutable and immutable variables.
|
2023-09-15 03:15:35 +00:00
|
|
|
|
2023-12-17 01:33:55 +00:00
|
|
|
## Immutable variables
|
2023-09-15 03:15:35 +00:00
|
|
|
|
2024-02-20 10:17:21 +00:00
|
|
|
Defined with `val`, followed by a variable name and a value.
|
2023-09-15 03:15:35 +00:00
|
|
|
|
|
|
|
```thp
|
2024-02-20 10:17:21 +00:00
|
|
|
val surname = "Doe"
|
|
|
|
val year_of_birth = 1984
|
2023-09-15 03:15:35 +00:00
|
|
|
```
|
|
|
|
|
2023-10-02 01:41:38 +00:00
|
|
|
### Datatype annotation
|
2023-09-15 03:15:35 +00:00
|
|
|
|
2024-02-20 10:17:21 +00:00
|
|
|
Written after the `val` keyword but before the variable name.
|
2023-09-15 03:15:35 +00:00
|
|
|
|
|
|
|
```thp
|
2024-02-20 10:17:21 +00:00
|
|
|
val String surname = "Doe"
|
|
|
|
val Int year_of_birth = 1984
|
2023-09-15 03:15:35 +00:00
|
|
|
```
|
|
|
|
|
2024-02-20 10:17:21 +00:00
|
|
|
When annotating an immutable variable the `val` keyword is optional
|
2023-09-15 03:15:35 +00:00
|
|
|
|
2023-12-17 01:33:55 +00:00
|
|
|
```thp
|
|
|
|
// Equivalent to the previous code
|
|
|
|
String surname = "Doe"
|
|
|
|
Int year_of_birth = 1984
|
|
|
|
```
|
2023-09-15 03:15:35 +00:00
|
|
|
|
2023-12-17 01:33:55 +00:00
|
|
|
This means that if a variable has only a datatype, it is immutable.
|
2023-09-15 03:15:35 +00:00
|
|
|
|
2023-12-17 01:33:55 +00:00
|
|
|
|
|
|
|
|
|
|
|
## Mutable variables
|
|
|
|
|
2024-02-20 10:17:21 +00:00
|
|
|
Defined with `var`, followed by a variable name and a value.
|
2023-09-15 03:15:35 +00:00
|
|
|
|
|
|
|
```thp
|
2024-02-20 10:17:21 +00:00
|
|
|
var name = "John"
|
|
|
|
var age = 32
|
2023-09-15 03:15:35 +00:00
|
|
|
```
|
|
|
|
|
2023-10-02 01:41:38 +00:00
|
|
|
### Datatype annotation
|
2023-09-15 03:15:35 +00:00
|
|
|
|
2024-02-20 10:17:21 +00:00
|
|
|
Written after the `var` keywords but before the variable name.
|
2023-09-15 03:15:35 +00:00
|
|
|
|
|
|
|
```thp
|
2024-02-20 10:17:21 +00:00
|
|
|
var String name = "John"
|
|
|
|
var Int age = 32
|
2023-09-15 03:15:35 +00:00
|
|
|
```
|
|
|
|
|
2024-02-20 10:17:21 +00:00
|
|
|
When annotating a mutable variable the keyword `var` is still **required**.
|
2023-09-15 03:15:35 +00:00
|
|
|
|
|
|
|
```thp
|
2023-10-02 01:41:38 +00:00
|
|
|
// Equivalent to the previous code
|
2024-02-20 10:17:21 +00:00
|
|
|
var String name = "John"
|
|
|
|
var Int age = 32
|
2023-09-15 03:15:35 +00:00
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|