at:tutorial:objects
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
at:tutorial:objects [2007/07/10 22:29] – * tvcutsem | at:tutorial:objects [2025/06/19 16:09] (current) – Removing uniform access information elisag | ||
---|---|---|---|
Line 94: | Line 94: | ||
def z := 0; | def z := 0; | ||
def sumOfSquares() { | def sumOfSquares() { | ||
- | super^sumOfSquares() + z*z | + | super^sumOfSquares() + z*z; |
}; | }; | ||
} | } | ||
Line 159: | Line 159: | ||
def Enumerable := object: { | def Enumerable := object: { | ||
def collect: closure { | def collect: closure { | ||
- | def c := clone: | + | def c := self.new([]); |
self.each: { |v| | self.each: { |v| | ||
- | c.add(closure(v)) | + | c.add(closure(v)); |
}; | }; | ||
+ | c; | ||
}; | }; | ||
}; | }; | ||
def Array := object: { | def Array := object: { | ||
def elements := []; | def elements := []; | ||
- | def init() { ... }; | + | def init(a) { elements := a; }; |
+ | def add(v) { elements := elements + [v]; self }; | ||
def collect: closure { | def collect: closure { | ||
Enumerable^collect: | Enumerable^collect: | ||
Line 173: | Line 175: | ||
def each: clo { | def each: clo { | ||
1.to: elements.length do: { |i| | 1.to: elements.length do: { |i| | ||
- | clo(elements[i]) | + | clo(elements[i]); |
}; | }; | ||
}; | }; | ||
Line 181: | Line 183: | ||
A message sent to an object using the '' | A message sent to an object using the '' | ||
- | Of course, the example above is a bit contrived: we could have just assigned '' | + | < |
+ | Array.add(1).add(2).add(3) | ||
+ | def c := Array.collect: | ||
+ | c.each: { |v| system.print(v)} // prints 234 | ||
+ | </ | ||
+ | |||
+ | Of course, the example above is a bit contrived: we could have just assigned '' | ||
Having described the semantics of '' | Having described the semantics of '' | ||
Line 221: | Line 229: | ||
> makeBankAccount(100).balance; | > makeBankAccount(100).balance; | ||
>> | >> | ||
- | <object:5068254> | + | <obj:{super, |
</ | </ | ||
+ | |||
+ | This pattern of creating objects by means of " | ||
+ | |||
+ | < | ||
+ | def b := makeBankAccount(100); | ||
+ | def b2 := b.new(); // shares its balance field with b! | ||
+ | b.deposit(10); | ||
+ | </ | ||
+ | |||
+ | In order to prevent this kind of errors, it is considered best practice to override '' | ||
+ | |||
+ | < | ||
+ | def makeBankAccount(balance) { | ||
+ | object: { | ||
+ | def new(@args) { makeBankAccount(@args) }; | ||
+ | def deposit(amnt) { /* as before */ }; | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | By overriding '' | ||
+ |
at/tutorial/objects.1184099376.txt.gz · Last modified: 2007/07/10 22:31 (external edit)