-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjects.ktg
More file actions
60 lines (49 loc) · 1.52 KB
/
objects.ktg
File metadata and controls
60 lines (49 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
; `object` declares a named template. `make` stamps a
; mutable instance (context!) from the template. Methods
; access the instance through `self`.
; --- Minimal shape ---
Counter: object [
field/optional [n [integer!] 0]
increment: does [self/n: self/n + 1]
value: does [self/n]
]
c: make Counter []
c/increment
c/increment
print c/value ; 2
; --- Required + optional fields ---
Person: object [
field/required [name [string!]]
field/required [age [integer!]]
field/optional [tag [string!] "friend"]
greet: does [
rejoin ["Hi, I'm " self/name " (" self/tag ")"]
]
]
p: make Person [name: "Kai" age: 30]
print p/greet ; Hi, I'm Kai (friend)
; --- Clone an instance ---
; `make` on an instance copies fields, applies overrides.
p2: make p [age: 25 tag: "rival"]
print p2/name ; Kai
print p2/age ; 25
print p2/tag ; rival
print p/age ; 30
; --- Methods with params ---
Account: object [
field/required [owner [string!]]
field/optional [balance [money!] $0.00]
deposit: function [amount [money!]] [
self/balance: self/balance + amount
]
summary: does [
rejoin [self/owner ": " self/balance]
]
]
a: make Account [owner: "Kai"]
a/deposit $50.00
a/deposit $12.34
print a/summary ; Kai: $62.34
; --- Templates are not mutable; instances are ---
; Mutating Counter directly would raise 'mutation'.
; Mutating `c` works -- instances are plain contexts.