at:tutorial:objects
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionNext revisionBoth sides next revision | ||
at:tutorial:objects [2007/07/10 22:21] – changed tvcutsem | at:tutorial:objects [2007/07/18 18:28] – jorge | ||
---|---|---|---|
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 add(v) { elements := elements + [v]; self }; |
def collect: closure { | def collect: closure { | ||
Enumerable^collect: | Enumerable^collect: | ||
}; | }; | ||
def each: clo { | def each: clo { | ||
- | 1.to: elements.length do: { |i| | + | 1.to: elements.length |
- | clo(elements[i]) | + | clo(elements[i]); |
}; | }; | ||
}; | }; | ||
Line 181: | Line 182: | ||
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)} | ||
+ | 2 | ||
+ | 3 | ||
+ | 4 | ||
+ | >> | ||
+ | </ | ||
+ | |||
+ | 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 202: | Line 215: | ||
===== Encapsulation ===== | ===== Encapsulation ===== | ||
- | In AmbientTalk, all fields and methods are " | + | |
+ | AmbientTalk | ||
< | < | ||
- | > def makeObject(hidden) { | + | def makeBankAccount(balance) { |
- | object: { | + | object: { |
- | def foo() { /* use hidden */ } | + | def deposit(amnt) { |
- | } | + | balance := balance + amnt; |
+ | " | ||
+ | }; | ||
} | } | ||
+ | } | ||
</ | </ | ||
- | Due to the encapsulation of this object the following | + | Because |
< | < | ||
- | > makeObject(5).hidden; | + | > makeBankAccount(100).balance; |
- | >> | + | >> |
< | < | ||
</ | </ |
at/tutorial/objects.txt · Last modified: 2013/05/17 20:23 by tvcutsem