Skip to content

Orientación a Objetos

Botlang tiene soporte para orientación a objetos en base a clases. Soporta herencia simple (no múltiple).

Definición de clases, creación de objetos, y envío de mensajes

 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
61
62
63
64
65
66
67
68
69
70
71
72
(defclass Product
    [attributes id category name price]
    [methods
        (init (fun (self id category name price)
            (@! self "id" id)
            (@! self "category" category)
            (@! self "name" name)
            (@! self "price" price)
        ))
    ]
)

;; Cheese es una categoría de Products
(defclass Cheese
    [extends Product]
    [methods
        (init (fun (self id name price)
            (super self "init" id "Cheese" name price)
        ))
    ]
)

;; Camembert está en la categoría 'Cheese' 
(defclass Camembert
    [extends Cheese]
    [methods
        (init (fun (self id price)
            (super self "init" id "Camembert" price)
        ))
    ]
)

;; Y necesitamos un carro para comprar nuestro queso
(defclass ShoppingCart
    [attributes
        (products (make-dict))
    ]
    [methods
        (add-product (fun (self product)
            (put! (@ self "products") (@ product "id") product)
        ))
        (get-products (fun (self)
            (map
                (fun (product) (send product "serialize"))
                (values (@ self "products"))
            )
        ))
    ]
)

;; Inicializamos un ShoppingCart
(define cart (new ShoppingCart))

;; Inicializamos y agregamos productos a nuestro carro de compra
(map
    (fun (product) (send cart "add-product" product))
    (list
        (new Cheese "id1" "Roquefort 100g" 4200)
        (new Camembert "id2" 3900)
    )
)

;; Creamos un bot-node
(bot entry-node (context message)
    (node-result
        (put context "carro" (send cart "get-products"))
        "Dejé tu carro en el contexto"
        end-node
    )
)

entry-node