Wiki

root/cobra/trunk/HowTo/282-PassReferencesToMethods.cobra

Revision 2335, 1.6 KB (checked in by Chuck.Esterbrook, 2 years ago)

Improvements to the How-To's.

  • Property svn:eol-style set to native
Line 
1"""
2You can refer to a method, rather than invoking it,
3by using the "ref" keyword before it.
4
5Invoking a method is far more popular than referencing/passing a method. So
6invocation is the syntactically clean case (obj.toString.trim) and method
7reference the verbose case (ref obj.someMethod). Also, the use of "ref"
8immediately clues you in to what's going on as you read code left-to-right.
9
10See the lines below marked with:   # <---
11"""
12
13
14class Customer
15
16    cue init(name as String, totalSpent as decimal)
17        base.init
18        _name = name
19        _totalSpent = totalSpent
20
21    get name from var as String
22
23    get totalSpent from var as decimal
24
25    def toString as String is override
26        # example: Snake Charmers LLC: $5,000.00
27        return '[.name]: [.totalSpent:C]'
28
29
30class Example
31
32    def main
33
34        customers = [
35            Customer('Yin Yang Inc.', 10_000.00),
36            Customer('Acme Inc.', 100_000.00),
37            Customer('Snake Charmers LLC', 5_000.00),
38        ]
39
40        print 'Ordered by name:'
41        customers.sort(ref .orderByName)  # <---
42        for cust in customers, print cust
43
44        print
45        print 'Ordered by total spent:'
46        customers.sort(ref .orderByTotalSpent)  # <---
47        for cust in customers, print cust
48
49        # you can localize the comparison code with a closure
50        customers.sort(do(a as Customer, b as Customer))
51            return a.name.toLower.compareTo(b.name.toLower)
52       
53        # or a lambda expression
54        customers.sort(do(a as Customer, b as Customer)=a.name.toLower.compareTo(b.name.toLower))
55
56    def orderByName(a as Customer, b as Customer) as int is shared
57        return a.name.toLower.compareTo(b.name.toLower)
58
59    def orderByTotalSpent(a as Customer, b as Customer) as int is shared
60        return a.totalSpent.compareTo(b.totalSpent)
Note: See TracBrowser for help on using the browser.