thp-web/md/learn/basics/variables.md

57 lines
911 B
Markdown
Raw Normal View History

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-10-02 01:41:38 +00:00
## Mutable variables
2023-09-15 03:15:35 +00:00
2023-10-02 01:41:38 +00:00
Defined with `var`, followed by a variable name and a value.
2023-09-15 03:15:35 +00:00
```thp
2023-10-02 01:41:38 +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
2023-10-02 01:41:38 +00:00
Written after the `var` keyword but before the variable name.
2023-09-15 03:15:35 +00:00
```thp
2023-10-02 01:41:38 +00:00
var String name = "John"
var Int age = 32
2023-09-15 03:15:35 +00:00
```
2023-10-02 01:41:38 +00:00
When annotating a mutable variable the keyword `var` is _required_.
2023-09-15 03:15:35 +00:00
2023-10-02 01:41:38 +00:00
## Immutable variables
2023-09-15 03:15:35 +00:00
2023-10-02 01:41:38 +00:00
Defined with `val`, followed by a variable name and a value.
2023-09-15 03:15:35 +00:00
```thp
2023-10-02 01:41:38 +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
2023-10-02 01:41:38 +00:00
Same as mutable variables
2023-09-15 03:15:35 +00:00
```thp
2023-10-02 01:41:38 +00:00
val String surname = "Doe"
val Int year_of_birth = 1984
2023-09-15 03:15:35 +00:00
```
2023-10-02 01:41:38 +00:00
When annotating an immutable variable the `val` keyword is optional
2023-09-15 03:15:35 +00:00
```thp
2023-10-02 01:41:38 +00:00
// Equivalent to the previous code
String surname = "Doe"
Int year_of_birth = 1984
2023-09-15 03:15:35 +00:00
```
2023-10-02 01:41:38 +00:00
This means that if a variable has only a datatype, it is immutable.
2023-09-15 03:15:35 +00:00