~jason2605/dictu/trunk

« back to all changes in this revision

Viewing changes to docs/docs/classes.md

  • Committer: GitHub
  • Author(s): Jason_000
  • Date: 2020-11-30 23:26:50 UTC
  • mfrom: (30.1.263)
  • Revision ID: git-v1:4923d4401e1b291604b053289ab9f435b10ee14d
Tags: v0.14.0
Merge pull request #340 from dictu-lang/develop

Release 0.14.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
47
47
SomeClass("Object created!"); // Object created!
48
48
```
49
49
 
 
50
### Implicit properties
 
51
 
 
52
Dictu actually has a way to define properties on the object without explicitly setting each variable passed into the constructor on the object through `this`.
 
53
 
 
54
```cs
 
55
class SomeClass {
 
56
    // The var keyword here makes the argument passed in be set as an instance variable
 
57
    init(var a, var b) {}
 
58
}
 
59
 
 
60
var obj = SomeClass(10, 20);
 
61
print("{} {}".format(obj.a, obj.b)); // "10 20"
 
62
```
 
63
 
 
64
The `var` keyword is optional on the constructor parameters, and can be in any order.
 
65
 
 
66
```cs
 
67
class SomeClass {
 
68
    init(var a, b, c, var d) {
 
69
        // b and c are not set as instance properties
 
70
    }
 
71
}
 
72
 
 
73
var obj = SomeClass(10, 20, 30, 40);
 
74
print("{} {} {} {}".format(
 
75
    obj.getAttribute("a"),
 
76
    obj.getAttribute("b"),
 
77
    obj.getAttribute("c"),
 
78
    obj.getAttribute("d")
 
79
)); // "10 nil nil 40"
 
80
```
 
81
 
50
82
## Methods
51
83
 
52
84
Methods are functions defined within a class. When defining a method in Dictu, the `def` keyword is not used and instead its just the method name and parameter list.
178
210
print(myObject.x); // 100
179
211
```
180
212
 
 
213
### Optional Chaining
 
214
 
 
215
Optional chaining allows you to read a property or method of an instance without explicitly having to check for `nil` before
 
216
attempting to access.
 
217
 
 
218
**Note:** If the left hand value is not nil the property / method **must** still exist when attempting to access otherwise a runtime error will occur.
 
219
 
 
220
```js
 
221
class Test {
 
222
    // Lets say you have a method that 
 
223
    // could return an object or nil
 
224
    someMethod() {
 
225
        return nil;
 
226
    }
 
227
    
 
228
    someOtherMethod() {
 
229
        print("method!");
 
230
    }
 
231
}
 
232
 
 
233
// Here there is no explicit nil check.
 
234
print(Test().someMethod()?.someOtherMethod()); // nil
 
235
 
 
236
// If the operand is not nil the method / property must exist  
 
237
print(Test()?.unknownMethod()); // Undefined property 'unknownMethod'.
 
238
``` 
 
239
 
181
240
## Class variables
182
241
 
183
242
A class variable, is a variable that is defined on the class and not the instance. This means that all instances of the class will have access