1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # This test provides variations on having an attribute with a default value but optionally settable with the constructor
16 # The main points of variation here is what are the basic exposed services and behavior
18 # The attribute is stored as not nullable but manual setter with a nullable signature is exposed
19 # Setting with `null` invoke the real setter with the default value.
20 # The manual setter is used as an initializer thus collected in the autoinit.
22 # Best option if one wants to allow the user to reset the default (with null) once the object is created
24 var s
: String is noautoinit
, private writable(real_s
=)
25 fun s
=(v
: nullable String) is autoinit
do self.real_s
= v
or else "Default"
28 # The attribute is stored as not nullable with standard automatic getter/setter
29 # The initializer is a manual method that accepts the nullable value and assigns the default value if null is given.
31 # Best option if the default can only be set a construction time
33 var s
: String is noautoinit
34 protected fun s_opt
=(v
: nullable String) is autoinit
do self.s
= v
or else "Default"
37 # The attribute is stored as nullable.
38 # A manual getter is used to return a default value if the attribute is null.
40 # Shortest solution without annotation.
41 # Con: the default is determined by the getter and never stored (this could be an issue if the default is complex)
43 protected var s_opt
: nullable String
44 fun s
: String do return s_opt
or else "Default"
47 # The attribute is stored as nullable.
48 # A manual getter is used to return a default value if the attribute is null.
50 # Longer solution without annotation but the getter lazily computes and stores the default once
52 protected var s_opt
: nullable String
55 if res
!= null then return res
62 # The attribute is stored as not nullable with standard automatic getter/setter
63 # The initializer is manual method that accepts the nullable value and does nothing if null is given.
65 # This one has a tricky behavior if one accesses to `s` before `s_opt=` is executed
67 var s
= "Default" is lazy
68 protected fun s_opt
=(v
: nullable String) is autoinit
do if v
!= null then s
= v
71 var a2
= new A
("Mine")
82 var b2
= new B
("Mine")
90 b1
.s_opt
= "Yet Another"
95 var c2
= new C
("Mine")
106 var d2
= new D
("Mine")
117 var e2
= new E
("Mine")
125 e1
.s_opt
= "Yet Another"