/
defaults.t
105 lines (80 loc) 路 2.62 KB
/
defaults.t
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use v6;
use Test;
plan 21;
# L<S12/Attributes/The value on the right is evaluated at object build time>
my $got_a_num; sub get_a_num { $got_a_num++; 42 }
my $got_a_str; sub get_a_str { $got_a_str++; "Pugs" }
my $got_a_code;
my $was_in_closure;
sub get_a_code {
$got_a_code++;
return {
$was_in_closure++;
42;
};
}
# L<S12/Attributes/the attribute being initialized>
my $set_by_code_attr;
class Foo {...}
eval 'class Foo {
has $.num = get_a_num();
has $.str = { get_a_str() };
has $.code = { get_a_code() };
has $.set_by_code = {
$set_by_code_attr := $_;
42;
};
has $.self_in_code = { self.echo };
method echo { "echo" }
}';
{
is $got_a_num, 1, "default should be called at compile-time";
my Foo $foo .= new;
is $got_a_num, 1, "default should be called only once, at compile-time (1)";
is $foo.num, 42, "attribute default worked";
is $got_a_num, 1, "default should be called only once, at compile-time (2)";
}
{
$got_a_str = 0; # reset
{
my Foo $foo .= new;
is $got_a_str, 1, "using a coderef as a default value delays execution";
is try { $foo.str }, "Pugs", "attribute default worked";
}
{
my Foo $foo .= new;
is $got_a_str, 2, "using a coderef as a default value delays execution";
is try { $foo.str }, "Pugs", "attribute default worked";
}
}
{
$got_a_code = 0; # reset
{
my Foo $foo .= new;
is $got_a_code, 1, "using a coderef as a default value delays execution";
is $was_in_closure, 0, "sub-coderef not yet executed";
try { $foo.code };
is $was_in_closure, 0, "sub-coderef still not executed";
}
{
my Foo $foo .= new;
is $got_a_code, 2, "using a coderef as a default value delays execution";
is $was_in_closure, 0, "sub-coderef not yet executed";
is try { $foo.code() }, 42, "sub-coderef execution works";
is $was_in_closure, 1, "sub-coderef still not executed";
}
}
{
my Foo $foo .= new;
is try { $foo.set_by_code }, 42, '$_ is the attribute being initialized (1)';
is $set_by_code_attr, 42, '$_ is the attribute being initialized (2)';
lives_ok { $set_by_code_attr++ },
'$_ is the attribute being initialized (3)';
is try { $foo.set_by_code }, 43, '$_ is the attribute being initialized (4)';
is $set_by_code_attr, 43, '$_ is the attribute being initialized (5)';
}
{
my Foo $foo .= new;
is try { $foo.self_in_code }, "echo", "self is the object being initialized";
}
# vim: ft=perl6