Wiki

root/cobra/trunk/Tests/240-generics/400-generic-methods/100-generic-method.cobra

Revision 1784, 0.9 KB (checked in by Chuck.Esterbrook, 3 years ago)

Code cleanup.

  • Property svn:eol-style set to native
Line 
1class Test
2
3    shared
4
5        def main
6            assert .join<of int>('', [1, 2, 3]) == '123'
7            assert .join<of String>(' ', ['a', 'b', 'c']) == 'a b c'
8            assert .same<of int>(5) == 5
9            assert .same<of Type>(Test) == Test
10            Test().run  # test generic methods that aren't shared
11
12        def join<of T>(separator as String, stuff as IEnumerable<of T>) as String
13            sb = StringBuilder()
14            sep = ''
15            for item in stuff
16                sb.append(sep)
17                sb.append(if(item is nil, 'nil', item.toString))  # use the CobraImp or CobraCore.toString()
18                sep = separator
19            return sb.toString
20
21        def same<of T>(t as T) as T  # test return value
22            x as T = t  # use generic type in body
23            return x
24
25    def run
26        i = 5
27        j = 6
28        .take2(i, j)
29        .swap(inout i, inout j)
30        assert i == 6 and j == 5
31
32    def take2<of T>(a as T, b as T)
33        pass
34
35    def swap<of T>(a as inout T, b as inout T)  # generic method with inout args
36        tmp = a
37        a = b
38        b = tmp
Note: See TracBrowser for help on using the browser.