-
Notifications
You must be signed in to change notification settings - Fork 23
/
immutable.html
1587 lines (1256 loc) · 142 KB
/
immutable.html
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"-->
<link rel="stylesheet" href="/gfx/bootstrap.min.css">
<link rel="stylesheet" href="/gfx/main.css">
<link rel="stylesheet" href="/gfx/code.css">
<title>Immutable objects</title>
</head>
<body class="page">
<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-PMJSKV"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-PMJSKV');</script>
<!-- End Google Tag Manager -->
<header>
<div class="container">
<a href="/">Immutables</a> ←
<h1>Immutable objects <iframe src="https://ghbtns.com/github-btn.html?user=immutables&repo=immutables&type=star&count=true&size=large" frameborder="0" scrolling="0" width="160px" height="30px"></iframe>
</h1>
</div>
</header>
<aside id="toc"></aside>
<section class="documentation">
<h2 id="overview">Overview</h2>
<p>To reap the benefits of immutability in Java, we created an annotation processor
to easily create simple and consistent value objects. You can think of it as
<a href="https://github.com/google/guava/wiki/ImmutableCollectionsExplained">Guava’s Immutable Collections</a> but for regular objects.</p>
<p>The core of <em>Immutables</em> is modelling. Good modelling is at the heart of creating good applications and
services, and of good design in general. We feel proud to fill a gap in the area of modelling in the Java programming language, where conventional JavaBeans are insufficient.</p>
<ul>
<li>Immutable objects are constructed once, in a consistent state, and can be safely shared
<ul>
<li>Will fail if mandatory attributes are missing</li>
<li>Cannot be sneakily modified when passed to other code</li>
</ul>
</li>
<li>Immutable objects are naturally thread-safe and can therefore be safely shared among threads
<ul>
<li>No excessive copying</li>
<li>No excessive synchronization</li>
</ul>
</li>
<li>Object definitions are pleasant to write and read
<ul>
<li>No boilerplate setter and getters</li>
<li>No ugly IDE-generated <code class="language-plaintext highlighter-rouge">hashCode</code>, <code class="language-plaintext highlighter-rouge">equals</code> and <code class="language-plaintext highlighter-rouge">toString</code> methods that end up being stored in source control.</li>
</ul>
</li>
</ul>
<p><a href="/getstarted.html">Get started!</a> Create an <em>abstract value class</em> and then add annotation to generate an <em>immutable implementation class</em>!</p>
<p>See <a href="/generated.html">sample generated code</a> for an example of the code generated by the processor,
or jump straight to the <a href="/immutable.html#features">features</a>!</p>
<h2 id="concepts">Concepts</h2>
<p><a name="abstract-value"></a></p>
<h3 id="abstract-value-type">Abstract value type</h3>
<p>An Abstract value type is a manually-written non-final (usually abstract) class or
interface (or even annotation type) that defines the value type and is annotated with the
<code class="language-plaintext highlighter-rouge">org.immutables.value.Value.Immutable</code> annotation.
It may contain <a href="#attributes">attributes</a> and other metadata, as well as regular Java methods (and fields, if necessary).
It is strongly recommended that abstract value types not introduce visible mutable state.
Abstract value types are used as the source model for generated code. <a href="/getstarted.html">Get started!</a>.</p>
<p><a name="attributes"></a></p>
<h3 id="attributes">Attributes</h3>
<p>An attribute holds a value that cannot be changed after the owning object is created.
The name “attribute” is used to intentionally distinguish the concept from “fields” or JavaBean “properties”, and to imply a similarity with Java annotation attributes.
It is defined by an accessor method: A zero argument, non-<code class="language-plaintext highlighter-rouge">void</code>-returning Java method.
No annotations are required on abstract accessor methods in order for them to become attributes. However, some attributes
such as those with <a href="#default-attribute">default values</a>
are non-<code class="language-plaintext highlighter-rouge">abstract</code> methods that have bodies that compute values.
Such accessors therefore require special annotations to distinguish them from regular methods.</p>
<h3 id="immutable-implementation-class">Immutable implementation class</h3>
<p>A <a href="/generated.html">Generated</a> <code class="language-plaintext highlighter-rouge">final</code> class that extends a manually-written <a href="#abstract-value">abstract value type</a>
and implements all declared accessor methods as well as supporting fields, methods, constructors, and a builder class.
An immutable implementation class implements abstract attribute accessors
for scalar primitive and object reference types, with special support provided for <a href="#collection">collection attributes</a>
and other types.
<code class="language-plaintext highlighter-rouge">java.lang.Object</code>’s <code class="language-plaintext highlighter-rouge">equals</code>, <code class="language-plaintext highlighter-rouge">hashCode</code>, and <code class="language-plaintext highlighter-rouge">toString</code> methods are overridden and fully dependent on attribute values
rather than on object identity.
Immutable implementation classes are the primary (but not the only) source code artifacts
generated by the <em>Immutables</em> annotation processor.</p>
<p><a name="features"></a></p>
<h2 id="features">Features</h2>
<h3 id="value">Value</h3>
<p>The annotation processor works by using annotated abstract value types as a model to generate immutable implementations.
A generated implementation extends or implements an abstract value type. Classes don’t have to be abstract if they don’t define abstract accessor methods.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">interface</span> <span class="nc">ValueInterface</span> <span class="o">{}</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">class</span> <span class="nc">ValueClass</span> <span class="o">{}</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="nd">@interface</span> <span class="nc">ValueAnnotation</span> <span class="o">{}</span>
<span class="o">...</span>
<span class="nc">ValueInterface</span> <span class="n">valueInterface</span> <span class="o">=</span> <span class="nc">ImmutableValueInterface</span><span class="o">.</span><span class="na">builder</span><span class="o">().</span><span class="na">build</span><span class="o">();</span>
<span class="nc">ValueClass</span> <span class="n">valueClass</span> <span class="o">=</span> <span class="nc">ImmutableValueClass</span><span class="o">.</span><span class="na">builder</span><span class="o">().</span><span class="na">build</span><span class="o">();</span>
<span class="nc">ValueAnnotation</span> <span class="n">valueAnnotation</span> <span class="o">=</span> <span class="nc">ImmutableValueAnnotation</span><span class="o">.</span><span class="na">builder</span><span class="o">().</span><span class="na">build</span><span class="o">();</span>
</code></pre></div></div>
<p><em>You can customize generated class names to have other prefixes than <code class="language-plaintext highlighter-rouge">Immutable*</code> or to have no prefix at all. See <a href="/style.html">styles</a></em>.</p>
<p>Nested abstract value types should be declared <code class="language-plaintext highlighter-rouge">static</code> if declared as inner classes (interfaces
and annotations are implicitly <code class="language-plaintext highlighter-rouge">static</code> if nested).</p>
<p><a name="include"></a></p>
<p>You are not limited to using classes that you control. You can generate immutable implementation
classes from the abstract types in other packages.</p>
<p>The <code class="language-plaintext highlighter-rouge">@Value.Include</code> annotation can be used on types and packages. This is most useful when you
want to generate implementations of annotations to use with DI libraries such as <em>Guice</em>. Inclusion
can be used in combination with <a href="/style.html#nesting"><code class="language-plaintext highlighter-rouge">@Value.Enclosing</code></a></p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">package</span> <span class="nn">my.package</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.lang.annotation.Retention</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.lang.annotation.RetentionPolicy</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">org.immutables.value.Value</span><span class="o">;</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Include</span><span class="o">({</span> <span class="nc">Retention</span><span class="o">.</span><span class="na">class</span> <span class="o">})</span>
<span class="kd">interface</span> <span class="nc">IncludedAnnotations</span> <span class="o">{}</span>
<span class="o">...</span>
<span class="nc">ImmutableRetention</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">value</span><span class="o">(</span><span class="nc">RetentionPolicy</span><span class="o">.</span><span class="na">CLASS</span><span class="o">);</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
</code></pre></div></div>
<p><a name="builder"></a></p>
<h3 id="builder">Builder</h3>
<p>By default, builders are generated for each immutable implementation class.
Builders enable expressive construction of objects using named attribute initializers.
Generally, builders compensate for the lack of named and optional constructor arguments in the Java language.</p>
<ul>
<li>To create a builder, invoke the static <code class="language-plaintext highlighter-rouge">builder()</code> method on a generated immutable implementation class</li>
<li>Invoke attribute initializer methods to set attributes</li>
<li>Call <code class="language-plaintext highlighter-rouge">build()</code> method to construct immutable instances after attributes are initialized</li>
</ul>
<p>The <code class="language-plaintext highlighter-rouge">build()</code> method will fail if any mandatory attribute is omitted. Efficient bit masks are used
internally to track which attributes are initialized!</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// builder methods illustrated</span>
<span class="nc">ImmutableValue</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">foo</span><span class="o">(</span><span class="mi">1442</span><span class="o">)</span>
<span class="o">.</span><span class="na">bar</span><span class="o">(</span><span class="kc">true</span><span class="o">)</span>
<span class="o">.</span><span class="na">addBuz</span><span class="o">(</span><span class="s">"a"</span><span class="o">)</span>
<span class="o">.</span><span class="na">addBuz</span><span class="o">(</span><span class="s">"1"</span><span class="o">,</span> <span class="s">"2"</span><span class="o">)</span>
<span class="o">.</span><span class="na">addAllBuz</span><span class="o">(</span><span class="n">iterable</span><span class="o">)</span>
<span class="o">.</span><span class="na">putQux</span><span class="o">(</span><span class="n">key</span><span class="o">,</span> <span class="n">value</span><span class="o">)</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
</code></pre></div></div>
<p><em>You can customize initialization methods to have prefixes like <code class="language-plaintext highlighter-rouge">set</code> or <code class="language-plaintext highlighter-rouge">with</code>, have builders created by constructor, have <code class="language-plaintext highlighter-rouge">create</code> methods, etc. See <a href="/style.html">styles</a></em>.</p>
<p>By default, builders have a method named <code class="language-plaintext highlighter-rouge">from</code>. The <code class="language-plaintext highlighter-rouge">from</code> method allows for “editing”
operations on immutable values by initializing the builder with attribute values taken
from an existing immutable object. This could be used to prevent structural sharing as happens with
<a href="#copy-methods">copy-methods</a>, or to accumulate collection elements from attributes of multiple
values.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="nc">ImmutableValue</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">from</span><span class="o">(</span><span class="n">otherValue</span><span class="o">)</span> <span class="c1">// merges attribute value into builder</span>
<span class="o">.</span><span class="na">addBuz</span><span class="o">(</span><span class="s">"b"</span><span class="o">)</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">from</code> method on builders is a much more sound and powerful alternative than having <code class="language-plaintext highlighter-rouge">toBuilder()</code> (or alike) on immutable values. For <a href="#strict-builder">strict builders</a>, <code class="language-plaintext highlighter-rouge">from</code>
methods are not generated as they’re prone to errors. If value object inherits abstract accessor definitions from super-types, than it would be possible to copy from super-type instance (of any implementation type) those attributes which are applicable. Generated <code class="language-plaintext highlighter-rouge">from</code> method will have overloads for each super-type from which we can get attribute values we inherit. Just to note: types parameterized with generics and accessors with covariant return type overrides will be excluded from such “from super-type” initialization.</p>
<p>If a particular builder has become redundant due to the presence of a <a href="#constructor">constructor</a>,
generation of the builder can be disabled using the <code class="language-plaintext highlighter-rouge">@Value.Immutable(builder = false)</code>
annotation parameter.</p>
<p>For advanced use cases, it may be desirable to have builders that produce different
types of objects but conform to the same interface, akin to the original
<a href="http://en.wikipedia.org/wiki/Builder_pattern">Builder pattern</a>. This is achievable by
declaring a static nested class named “Builder” which will be extended by the generated builder.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">interface</span> <span class="nc">Vehicle</span> <span class="o">{</span>
<span class="o">}</span>
<span class="kd">interface</span> <span class="nc">VehicleBuilder</span> <span class="o">{</span>
<span class="c1">// Generated builders will implement this method</span>
<span class="c1">// It is compatible with signature of generated builder methods where</span>
<span class="c1">// return type is narrowed to Scooter or Automobile</span>
<span class="nc">Vehicle</span> <span class="nf">build</span><span class="o">();</span>
<span class="o">}</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">Scooter</span> <span class="kd">implements</span> <span class="nc">Vehicle</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">static</span> <span class="kd">class</span> <span class="nc">Builder</span> <span class="kd">implements</span> <span class="nc">VehicleBuilder</span> <span class="o">{}</span>
<span class="o">}</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">Automobile</span> <span class="kd">implements</span> <span class="nc">Vehicle</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">static</span> <span class="kd">class</span> <span class="nc">Builder</span> <span class="kd">implements</span> <span class="nc">VehicleBuilder</span> <span class="o">{}</span>
<span class="o">}</span>
<span class="kd">class</span> <span class="nc">Builders</span> <span class="o">{</span>
<span class="kt">void</span> <span class="nf">buildIt</span><span class="o">(</span><span class="nc">VehicleBuilder</span> <span class="n">builder</span><span class="o">)</span> <span class="o">{</span>
<span class="nc">Vehicle</span> <span class="n">vehicle</span> <span class="o">=</span> <span class="n">builder</span><span class="o">.</span><span class="na">build</span><span class="o">();</span>
<span class="o">}</span>
<span class="kt">void</span> <span class="nf">use</span><span class="o">()</span> <span class="o">{</span>
<span class="n">buildIt</span><span class="o">(</span><span class="nc">ImmutableScooter</span><span class="o">.</span><span class="na">builder</span><span class="o">());</span>
<span class="n">buildIt</span><span class="o">(</span><span class="nc">ImmutableAutomobile</span><span class="o">.</span><span class="na">builder</span><span class="o">());</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>An explicitly declared abstract “Builder” could specify all needed <code class="language-plaintext highlighter-rouge">extends</code> or <code class="language-plaintext highlighter-rouge">implements</code>
declarations in addition to having convenience methods that will show up on the generated builder.
However, special care should be taken in order to maintain the structural compatibility of
declared builder super-types and generated builders to prevent compile-time type errors from
appearing in the generated code.</p>
<p>Using “forwarding” factory methods and abstract builders, it is possible to hide the generated
implementation type and its builder from the API. See this <a href="#hide-implementation">example</a>.</p>
<p>Another structural customization for builders involves having a private immutable implementation
class, hidden inside the builder, which is then generated as a standalone top-level builder
class in the same package.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Style</span><span class="o">(</span><span class="n">visibility</span> <span class="o">=</span> <span class="nc">ImplementationVisibility</span><span class="o">.</span><span class="na">PRIVATE</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">Person</span> <span class="o">{</span>
<span class="nc">String</span> <span class="nf">getName</span><span class="o">();</span>
<span class="nc">String</span> <span class="nf">getAddress</span><span class="o">();</span>
<span class="o">}</span>
<span class="nc">Person</span> <span class="n">person</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">PersonBuilder</span><span class="o">()</span>
<span class="o">.</span><span class="na">name</span><span class="o">(</span><span class="s">"Jim Boe"</span><span class="o">)</span>
<span class="o">.</span><span class="na">address</span><span class="o">(</span><span class="s">"P.O. box 0001, Lexington, KY"</span><span class="o">)</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
</code></pre></div></div>
<p><a name="extending-builder"></a>
From version <code class="language-plaintext highlighter-rouge">2.0.17</code> onwards, it is possible to extend a [yet-to-be] generated builder to code
in the following style:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Style</span><span class="o">(</span><span class="n">visibility</span> <span class="o">=</span> <span class="nc">ImplementationVisibility</span><span class="o">.</span><span class="na">PACKAGE</span><span class="o">,</span> <span class="n">overshadowImplementation</span> <span class="o">=</span> <span class="kc">true</span><span class="o">)</span>
<span class="c1">//...</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">Person</span> <span class="o">{</span>
<span class="nc">String</span> <span class="nf">name</span><span class="o">();</span>
<span class="nc">String</span> <span class="nf">address</span><span class="o">();</span>
<span class="c1">// static inner class Builder extends generated or yet to be generated Builder</span>
<span class="kd">class</span> <span class="nc">Builder</span> <span class="kd">extends</span> <span class="nc">ImmutablePerson</span><span class="o">.</span><span class="na">Builder</span> <span class="o">{}</span>
<span class="o">}</span>
<span class="nc">Person</span> <span class="n">person</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Person</span><span class="o">.</span><span class="na">Builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">name</span><span class="o">(</span><span class="s">"Jim Boe"</span><span class="o">)</span>
<span class="o">.</span><span class="na">address</span><span class="o">(</span><span class="s">"P.O. box 0000, Lexington, KY"</span><span class="o">)</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
</code></pre></div></div>
<p>While <code class="language-plaintext highlighter-rouge">ImmutablePerson</code> (and <code class="language-plaintext highlighter-rouge">ImmutablePerson.Builder</code> consequently) is not visible outside of package, <code class="language-plaintext highlighter-rouge">Person.Builder</code> inherits and exposes all public methods defined on <code class="language-plaintext highlighter-rouge">ImmutablePerson.Builder</code>.
The <code class="language-plaintext highlighter-rouge">overshadowImplementation = true</code> style attribute makes sure that <code class="language-plaintext highlighter-rouge">build()</code> will be declared to return abstract value type <code class="language-plaintext highlighter-rouge">Person</code>, not the implementation <code class="language-plaintext highlighter-rouge">ImmutablePerson</code>, following metaphor: implementation type will be “overshadowed” by abstract value type.
The interesting fact is that the calling bytecode references only <code class="language-plaintext highlighter-rouge">Person.Builder</code> and not <code class="language-plaintext highlighter-rouge">ImmutablePerson.Builder</code>. From the above example: <code class="language-plaintext highlighter-rouge">INVOKEVIRTUAL</code> will target <code class="language-plaintext highlighter-rouge">Person.Builder.name</code>, <code class="language-plaintext highlighter-rouge">Person.Builder.address</code> and <code class="language-plaintext highlighter-rouge">Person.Builder.build</code> methods. Essentially, a generated class becomes implementation detail without much boilerplate which is needed to fully <a href="#hide-implementation">hide implementation</a> behind user-written code.</p>
<p>For other structural and naming style customizations, see the <a href="/style.html">style guide</a>.</p>
<p><a name="strict-builder"></a></p>
<h3 id="strict-builder">Strict Builder</h3>
<p>By setting the <code class="language-plaintext highlighter-rouge">strictBuilder</code> style parameter (<code class="language-plaintext highlighter-rouge">@Value.Style(strictBuilder = true, ...)</code>),
you can instruct generated builders to operate in <em>strict mode</em>: only forward-only
initialization is possible. In other words, only
additive operations are available on collection attributes, and regular
attributes can be set only once. Strict builders enable early error detection
during initialization, such as misspellings or copy-paste leftovers. This makes
builders even more similar to object literal expressions. Strict mode is off
by default: regular builders are generated in a way that allows the resetting
of previously set values.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Style</span><span class="o">(</span><span class="n">strictBuilder</span> <span class="o">=</span> <span class="kc">true</span><span class="o">)</span>
<span class="kd">interface</span> <span class="nc">Aar</span> <span class="o">{</span>
<span class="kt">boolean</span> <span class="nf">a</span><span class="o">();</span>
<span class="nc">Integer</span> <span class="nf">b</span><span class="o">();</span>
<span class="o">}</span>
<span class="nc">ImmutableAar</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">a</span><span class="o">(</span><span class="kc">true</span><span class="o">)</span>
<span class="o">.</span><span class="na">b</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span>
<span class="o">.</span><span class="na">b</span><span class="o">(</span><span class="mi">2</span><span class="o">)</span> <span class="c1">// IllegalStateException will be thrown here, 'b' cannot be reinitialized</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
</code></pre></div></div>
<p>No methods to reset collections are generated on strict builders. Additionally, no <code class="language-plaintext highlighter-rouge">from</code> method is generated. Those methods would be error-inducing in strict mode.</p>
<p>Note that it is not recommended to use <code class="language-plaintext highlighter-rouge">@Value.Style</code> directly on abstract value type; use it directly only during experimentation.
The preferred method to use <code class="language-plaintext highlighter-rouge">Style</code> annotations is to create meta-annotations as described in the <a href="/style.html">style guide</a>.</p>
<h3 id="staged-builder">Staged builder</h3>
<p>The experimental new feature (since 2.3.2) allows you to enable generation of “staged builders” (aka “telescopic builders”). The mode is activated using <code class="language-plaintext highlighter-rouge">@Value.Style(stagedBuilder = true)</code> style attribute. A staged builder is a compile-time safe way to ensure that all required attributes are set. The API, composed of stage interfaces, forces initialization of mandatory attributes in stages, one by one, guiding via code-completion and making it impossible to even call <code class="language-plaintext highlighter-rouge">build()</code> before all are set. This guarantees that final <code class="language-plaintext highlighter-rouge">build()</code> call will not throw <code class="language-plaintext highlighter-rouge">IllegalStateException</code> for missing attributes. All remaining optional, nullable and collection attributes can be initialized on a final stage in any order. An addition, removal or change of the source order of the required attributes will cause compilation error for all builder usages and have to be corrected.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Style</span><span class="o">(</span><span class="n">stagedBuilder</span> <span class="o">=</span> <span class="kc">true</span><span class="o">)</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">Person</span> <span class="o">{</span>
<span class="nc">String</span> <span class="nf">name</span><span class="o">();</span>
<span class="kt">int</span> <span class="nf">age</span><span class="o">();</span>
<span class="kt">boolean</span> <span class="nf">isEmployed</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">...</span>
<span class="nc">ImmutablePerson</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">name</span><span class="o">(</span><span class="s">"Billy Bounce"</span><span class="o">)</span>
<span class="o">.</span><span class="na">age</span><span class="o">(</span><span class="mi">33</span><span class="o">)</span>
<span class="o">.</span><span class="na">isEmployed</span><span class="o">(</span><span class="kc">false</span><span class="o">)</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
<span class="o">...</span>
<span class="c1">// under the hood</span>
<span class="kd">public</span> <span class="kd">final</span> <span class="kd">class</span> <span class="nc">ImmutablePerson</span> <span class="kd">implements</span> <span class="nc">Person</span> <span class="o">{</span>
<span class="o">...</span>
<span class="kd">public</span> <span class="kd">static</span> <span class="nc">NameBuildStage</span> <span class="nf">builder</span><span class="o">()</span> <span class="o">{</span> <span class="o">...</span> <span class="o">}</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">NameBuildStage</span> <span class="o">{</span> <span class="nc">AgeBuildStage</span> <span class="nf">name</span><span class="o">(</span><span class="nc">String</span> <span class="n">name</span><span class="o">);</span> <span class="o">}</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">AgeBuildStage</span> <span class="o">{</span> <span class="nc">IsEmployedBuildStage</span> <span class="nf">age</span><span class="o">(</span><span class="kt">int</span> <span class="n">age</span><span class="o">);</span> <span class="o">}</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">IsEmployedBuildStage</span> <span class="o">{</span> <span class="nc">BuildFinal</span> <span class="nf">isEmployed</span><span class="o">(</span><span class="kt">boolean</span> <span class="n">isEmployed</span><span class="o">);</span> <span class="o">}</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">BuildFinal</span> <span class="o">{</span> <span class="nc">ImmutablePerson</span> <span class="nf">build</span><span class="o">();</span> <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>The price to pay for the additional compile-time safety is the increased count of java interfaces, generated per each required attribute. If staged builders are used extensively, this may lead to the increased memory/disc footprint and can affect class-loading time.</p>
<p>The staged builder mode also implies <a href="#strict-builder">strict builder</a> mode.</p>
<p><a name="constructor"></a></p>
<h3 id="constructor-method">Constructor method</h3>
<p>As an alternative to builders, it is possible to provide concise “constructor” factory methods.
A “constructor” will be available as a <code class="language-plaintext highlighter-rouge">static</code> method named <code class="language-plaintext highlighter-rouge">of</code>, on generated immutable implementation classes.</p>
<p>In order to generate a constructor method, certain attributes have to be annotated
with <code class="language-plaintext highlighter-rouge">org.immutables.value.Value.Parameter</code> annotations.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">HostWithPort</span> <span class="o">{</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Parameter</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="nc">String</span> <span class="nf">hostname</span><span class="o">();</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Parameter</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kt">int</span> <span class="nf">port</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">...</span>
<span class="nc">HostWithPort</span> <span class="n">hostWithPort</span> <span class="o">=</span> <span class="nc">ImmutableHostWithPort</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="s">"localhost"</span><span class="o">,</span> <span class="mi">8081</span><span class="o">);</span>
<span class="kt">boolean</span> <span class="n">willBeTrue</span> <span class="o">=</span> <span class="n">hostWithPort</span><span class="o">.</span><span class="na">equals</span><span class="o">(</span>
<span class="nc">ImmutableHostWithPort</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">hostname</span><span class="o">(</span><span class="s">"localhost"</span><span class="o">)</span>
<span class="o">.</span><span class="na">port</span><span class="o">(</span><span class="mi">8081</span><span class="o">)</span>
<span class="o">.</span><span class="na">build</span><span class="o">());</span>
</code></pre></div></div>
<p>You can optionally specify the ordering of parameters using <code class="language-plaintext highlighter-rouge">order</code> annotation attributes,
to ensure that the order of constructor parameters does not differ between Java compilers
(Java compilers do not necessarily preserve the order of declarations). Source ordering currently
works for <code class="language-plaintext highlighter-rouge">javac</code> and Eclipse JDT compilers.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">HostWithPort</span> <span class="o">{</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Parameter</span><span class="o">(</span><span class="n">order</span> <span class="o">=</span> <span class="mi">2</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kt">int</span> <span class="nf">port</span><span class="o">();</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Parameter</span><span class="o">(</span><span class="n">order</span> <span class="o">=</span> <span class="mi">1</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="nc">String</span> <span class="nf">hostname</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">...</span>
<span class="nc">HostWithPort</span> <span class="n">hostWithPort</span> <span class="o">=</span> <span class="nc">ImmutableHostWithPort</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="s">"localhost"</span><span class="o">,</span> <span class="mi">8081</span><span class="o">);</span>
</code></pre></div></div>
<p>If you want to automatically turn all attributes into parameters to generate constructor, you could use styles for that, see <a href="#tuples">tuple style</a> pattern.</p>
<h4 id="plain-public-constructor">Plain public constructor</h4>
<p>If there’s a need for plain public constructor instead of the factory method we can achieve it using <a href="style.html">styles</a> by “renaming” <code class="language-plaintext highlighter-rouge">of</code> method to <code class="language-plaintext highlighter-rouge">new</code>:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Style</span><span class="o">(</span>
<span class="n">of</span> <span class="o">=</span> <span class="s">"new"</span><span class="o">,</span> <span class="c1">// renames "of" method to "new", which is interpreted as plain constructor</span>
<span class="n">allParameters</span> <span class="o">=</span> <span class="kc">true</span> <span class="c1">// unrelated to the line above: every attribute becomes parameter</span>
<span class="c1">// reminder: don't get used to inline styles, read style guide!</span>
<span class="o">)</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">HostWithPort</span> <span class="o">{</span>
<span class="nc">String</span> <span class="nf">host</span><span class="o">();</span>
<span class="kt">int</span> <span class="nf">port</span><span class="o">();</span>
<span class="o">}</span>
<span class="nc">HostWithPort</span> <span class="n">hostWithPort</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">ImmutableHostWithPort</span><span class="o">(</span><span class="s">"localhost"</span><span class="o">,</span> <span class="mi">8081</span><span class="o">);</span>
</code></pre></div></div>
<p><strong>Things to be aware of</strong></p>
<ul>
<li>If not all mandatory attributes are marked as <code class="language-plaintext highlighter-rouge">@Value.Parameter</code>
<ul>
<li>Compilation error: could not generate default value for mandatory field.</li>
</ul>
</li>
</ul>
<p><a name="collection"></a></p>
<h3 id="array-collection-and-map-attributes">Array, Collection and Map attributes</h3>
<p>Following collection types enjoy built-in support for convenient usage:</p>
<ul>
<li>
<p><code class="language-plaintext highlighter-rouge">T[]</code></p>
</li>
<li>
<p><code class="language-plaintext highlighter-rouge">java.util.List<T></code></p>
</li>
<li>
<p><code class="language-plaintext highlighter-rouge">java.util.Set<T></code></p>
</li>
<li>
<p><code class="language-plaintext highlighter-rouge">java.util.Map<K, V></code></p>
</li>
<li>
<p><code class="language-plaintext highlighter-rouge">com.google.common.collect.Multiset<T></code></p>
</li>
<li>
<p><code class="language-plaintext highlighter-rouge">com.google.common.collect.Multimap<K, V></code> (<code class="language-plaintext highlighter-rouge">ListMultimap</code>, <code class="language-plaintext highlighter-rouge">SetMultimap</code>)</p>
</li>
<li>
<p><code class="language-plaintext highlighter-rouge">com.google.common.collect.BiMap<K, V></code></p>
</li>
<li>
<p><code class="language-plaintext highlighter-rouge">com.google.common.collect.Immutable*</code> variants for collections above</p>
</li>
</ul>
<p>Array attributes are cloned for safety (due to the mutable nature of Java arrays).
Collection attributes are backed by Guava immutable collections if Guava is available on the classpath.
Otherwise, they are safely copied and wrapped in unmodifiable collection classes from the standard JDK.</p>
<p><code class="language-plaintext highlighter-rouge">java.util.Set</code> and <code class="language-plaintext highlighter-rouge">java.util.Map</code> with <code class="language-plaintext highlighter-rouge">enum</code> keys are backed by efficient <code class="language-plaintext highlighter-rouge">EnumSet</code> and <code class="language-plaintext highlighter-rouge">EnumMap</code> implementations.</p>
<p><a name="natural-reverse"></a>
Ordered maps and sets are recognized for natural and reverse natural ordering
using <code class="language-plaintext highlighter-rouge">@Value.NaturalOrder</code> and <code class="language-plaintext highlighter-rouge">@Value.ReverseOrder</code> annotations, respectively.</p>
<ul>
<li>
<p><code class="language-plaintext highlighter-rouge">java.util.SortedSet<T></code></p>
</li>
<li>
<p><code class="language-plaintext highlighter-rouge">java.util.NavigableSet<T></code></p>
</li>
<li>
<p><code class="language-plaintext highlighter-rouge">java.util.SortedMap<K, V></code></p>
</li>
<li>
<p><code class="language-plaintext highlighter-rouge">java.util.NavigableMap<K, V></code></p>
</li>
</ul>
<p>Without ordering annotations, ordered sets and maps attributes will be generated as regular
attributes to support construction with custom comparators, etc.</p>
<p>All mentioned above collection types could be also declared as Guava’s immutable collections
<code class="language-plaintext highlighter-rouge">com.google.common.collect.Immutable*</code>. Please note that other collection <em>implementations</em>
such as <code class="language-plaintext highlighter-rouge">java.util.ArrayList</code> will not be recognized as special collection attributes.</p>
<p>When building using builders, the contents of collection attributes can be left unspecified.
It is possible to verify, for example, that they contain a required number of items using <a href="#check-method">Precondition check methods</a>.</p>
<p><a href="#builder">Builders</a> have special methods to initialize collection attributes:</p>
<ul>
<li>For an array attribute named <code class="language-plaintext highlighter-rouge">foo</code>, where elements are of type <code class="language-plaintext highlighter-rouge">T</code>
<ul>
<li><code class="language-plaintext highlighter-rouge">foo(T...)</code></li>
</ul>
</li>
<li>For a <code class="language-plaintext highlighter-rouge">List</code>, <code class="language-plaintext highlighter-rouge">Set</code>, or <code class="language-plaintext highlighter-rouge">Multiset</code> attribute named <code class="language-plaintext highlighter-rouge">foo</code>, where elements are of type <code class="language-plaintext highlighter-rouge">T</code>
<ul>
<li><code class="language-plaintext highlighter-rouge">foo(Iterable<? extends T>)</code> — not available in <a href="#strict-builder">strict</a> mode</li>
<li><code class="language-plaintext highlighter-rouge">addFoo(T)</code></li>
<li><code class="language-plaintext highlighter-rouge">addFoo(T...)</code></li>
<li><code class="language-plaintext highlighter-rouge">addAllFoo(Iterable<? extends T>)</code></li>
</ul>
</li>
<li>For a <code class="language-plaintext highlighter-rouge">Map</code> or <code class="language-plaintext highlighter-rouge">BiMap</code> attribute named <code class="language-plaintext highlighter-rouge">bar</code>, where keys are of type <code class="language-plaintext highlighter-rouge">K</code> and values of type <code class="language-plaintext highlighter-rouge">V</code>
<ul>
<li><code class="language-plaintext highlighter-rouge">bar(Map<? extends K, ? extends V>)</code> — not available in <a href="#strict-builder">strict</a> mode</li>
<li><code class="language-plaintext highlighter-rouge">putBar(K, V)</code></li>
<li><code class="language-plaintext highlighter-rouge">putBar(Map.Entry<? extends K, ? extends V>)</code></li>
<li><code class="language-plaintext highlighter-rouge">putAllBar(Map<? extends K, ? extends V>)</code></li>
</ul>
</li>
<li>For a <code class="language-plaintext highlighter-rouge">Multimap</code> attribute named <code class="language-plaintext highlighter-rouge">bar</code>
<ul>
<li><code class="language-plaintext highlighter-rouge">bar(Multimap<? extends K, ? extends V>)</code> — not available in <a href="#strict-builder">strict</a> mode</li>
<li><code class="language-plaintext highlighter-rouge">putBar(K, V)</code></li>
<li><code class="language-plaintext highlighter-rouge">putBar(Map.Entry<? extends K, ? extends V>)</code></li>
<li><code class="language-plaintext highlighter-rouge">putBar(K, ...V)</code></li>
<li><code class="language-plaintext highlighter-rouge">putAllBar(K, Iterable<V>)</code></li>
<li><code class="language-plaintext highlighter-rouge">putAllBar(Multimap<? extends K, ? extends V>)</code></li>
</ul>
</li>
</ul>
<p>From version <code class="language-plaintext highlighter-rouge">0.16</code> onwards, we no longer generate <code class="language-plaintext highlighter-rouge">clear*</code> methods on builders, so <code class="language-plaintext highlighter-rouge">clearFoo()</code> or <code class="language-plaintext highlighter-rouge">clearBar()</code> would not be generated for collection or map attributes.
To clear the contents of collections or maps, use a reset method <code class="language-plaintext highlighter-rouge">bar(Collections.emptyList())</code>, or use <a href="#copy-methods">copy methods</a> right after an instance is built.</p>
<p>Since version <code class="language-plaintext highlighter-rouge">2.1.11</code> you can use opt-in <a href="style.html#depluralization">depluralization</a> to generate methods named <code class="language-plaintext highlighter-rouge">addFoo</code> or <code class="language-plaintext highlighter-rouge">putFoo</code> derived from collection attribute named <code class="language-plaintext highlighter-rouge">foos</code>.</p>
<p>The set of methods was chosen to represent the minimum required for convenient use. A smaller
selection of methods resulted in noisy conversions all over the code using the generated types. A
bigger selection of methods resulted in a kitchen-sink effect (in effect, duplicating a mutable
collection API!). If you are concerned with the number of methods, consider using tools like
<em>ProGuard</em> to remove unused generated methods in the resulting application.</p>
<p>Why are other kinds of containers not supported in the same way? What about <code class="language-plaintext highlighter-rouge">java.lang.Iterable</code>, <code class="language-plaintext highlighter-rouge">java.util.Collection</code> or <code class="language-plaintext highlighter-rouge">java.util.Queue</code>?
Those other containers are either too-generic or too-specific for the purposes of immutable object modelling.
This might change upon request, of course, and this is what happened with ordered sets and maps (which were recognized with <a href="#natural-reverse">order annotations</a>).
On the plus side, any type is supported as an attribute value. Even though there isn’t any kind of magic support, other container types are still usable:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">DoItYourselfContainer</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="nc">Iterable</span><span class="o"><</span><span class="nc">String</span><span class="o">></span> <span class="nf">iterable</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">...</span>
<span class="nc">ImmutableDoItYourselfContainer</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">iterable</span><span class="o">(</span><span class="nc">ImmutableSet</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="s">"a"</span><span class="o">,</span> <span class="s">"b"</span><span class="o">,</span> <span class="s">"c"</span><span class="o">))</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
</code></pre></div></div>
<p><a name="optional"></a></p>
<h3 id="optional-attributes">Optional attributes</h3>
<p>An attribute declared with a return type of <code class="language-plaintext highlighter-rouge">com.google.common.base.Optional<T></code>
defines a logically <a href="https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained#optional">optional</a>
attribute of type <code class="language-plaintext highlighter-rouge">T</code>.</p>
<p>As of version 2.0, <code class="language-plaintext highlighter-rouge">java.util.Optional</code>, <code class="language-plaintext highlighter-rouge">java.util.OptionalInt</code>, <code class="language-plaintext highlighter-rouge">java.util.OptionalLong</code>, <code class="language-plaintext highlighter-rouge">java.util.OptionalDouble</code> from Java 8 are also fully supported.</p>
<p>As of version 2.1.1, <code class="language-plaintext highlighter-rouge">com.atlassian.fugue.Option</code> and <code class="language-plaintext highlighter-rouge">io.atlassian.fugue.Option</code> are also supported.</p>
<p>Optional values can be omitted when building objects, and will default to <code class="language-plaintext highlighter-rouge">Optional.absent()</code> (or <code class="language-plaintext highlighter-rouge">Optional.empty()</code> in Java 8).
Generated builders have special initializers for optional attributes:</p>
<ul>
<li>For an optional attribute named <code class="language-plaintext highlighter-rouge">opt</code>, where elements are of type <code class="language-plaintext highlighter-rouge">T</code>
<ul>
<li><code class="language-plaintext highlighter-rouge">opt(T)</code> sets present value for T</li>
<li><code class="language-plaintext highlighter-rouge">opt(Optional<T>)</code> specifies present or absent</li>
</ul>
</li>
</ul>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">java.util.*</span><span class="o">;</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">AllOptional</span> <span class="o">{</span>
<span class="n">com</span><span class="o">.</span><span class="na">google</span><span class="o">.</span><span class="na">common</span><span class="o">.</span><span class="na">base</span><span class="o">.</span><span class="na">Optional</span><span class="o"><</span><span class="nc">Integer</span><span class="o">></span> <span class="nf">v1</span><span class="o">();</span>
<span class="nc">Optional</span><span class="o"><</span><span class="nc">Integer</span><span class="o">></span> <span class="nf">v2</span><span class="o">();</span>
<span class="nc">OptionalInt</span> <span class="nf">i1</span><span class="o">();</span>
<span class="nc">OptionalLong</span> <span class="nf">l1</span><span class="o">();</span>
<span class="nc">OptionalDouble</span> <span class="nf">d1</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">...</span>
<span class="c1">// No error as all values are optional</span>
<span class="nc">ImmutableAllOptional</span><span class="o">.</span><span class="na">builder</span><span class="o">().</span><span class="na">build</span><span class="o">();</span>
<span class="nc">ImmutableAllOptional</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">v1</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span>
<span class="o">.</span><span class="na">v2</span><span class="o">(</span><span class="mi">2</span><span class="o">)</span>
<span class="o">.</span><span class="na">i1</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span>
<span class="o">.</span><span class="na">l1</span><span class="o">(</span><span class="mi">1L</span><span class="o">)</span>
<span class="o">.</span><span class="na">d1</span><span class="o">(</span><span class="mf">1.0</span><span class="o">)</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
</code></pre></div></div>
<p><a name="default-attribute"></a></p>
<h3 id="default-attributes">Default attributes</h3>
<p>Attributes can have default values provided when none are specified to a <a href="#builder">builder</a>.
To declare a default attribute value, create a non-abstract attribute initializer method
and annotate it with <code class="language-plaintext highlighter-rouge">org.immutables.value.Value.Default</code>. If the value is omitted during
construction, this initializer method will be called to retrieve a default value for the attribute.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">PlayerInfo</span> <span class="o">{</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Parameter</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kt">long</span> <span class="nf">id</span><span class="o">();</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Default</span>
<span class="kd">public</span> <span class="nc">String</span> <span class="nf">name</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="s">"Anonymous_"</span> <span class="o">+</span> <span class="n">id</span><span class="o">();</span>
<span class="o">}</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Default</span>
<span class="kd">public</span> <span class="kt">int</span> <span class="nf">gamesPlayed</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="mi">0</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">...</span>
<span class="nc">PlayerInfo</span> <span class="n">veteran</span> <span class="o">=</span> <span class="nc">ImmutablePlayerInfo</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">id</span><span class="o">(</span><span class="mi">1</span><span class="o">)</span>
<span class="o">.</span><span class="na">name</span><span class="o">(</span><span class="s">"Fiddler"</span><span class="o">)</span>
<span class="o">.</span><span class="na">gamesPlayed</span><span class="o">(</span><span class="mi">99</span><span class="o">)</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
<span class="nc">PlayerInfo</span> <span class="n">anonymous44</span> <span class="o">=</span> <span class="nc">ImmutablePlayerInfo</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="mi">44</span><span class="o">);</span>
<span class="nc">String</span> <span class="n">name</span> <span class="o">=</span> <span class="n">anonymous44</span><span class="o">.</span><span class="na">name</span><span class="o">();</span> <span class="c1">// Anonymous_44</span>
</code></pre></div></div>
<p>Since version <code class="language-plaintext highlighter-rouge">2.1</code>, a default attribute initializer method’s body can refer to other default
or derived attributes as long as this does not introduce initialization cycles.
If a cycle is introduced, then an <code class="language-plaintext highlighter-rouge">IllegalStateException</code> will be thrown pointing
to attributes which form a cycle.</p>
<p>There’s no need to use <code class="language-plaintext highlighter-rouge">@Value.Default</code> to return empty collections as collection attributes are empty by default if not initialized.
Since version <code class="language-plaintext highlighter-rouge">2.2</code>. <code class="language-plaintext highlighter-rouge">@Value.Default</code> and <code class="language-plaintext highlighter-rouge">@Nullable</code> <a href="#collection">collection attributes</a> are supported so you can provide default value if no values have been provided but empty collection or <code class="language-plaintext highlighter-rouge">null</code> (if nullable) can be set.</p>
<p>For immutable <a href="#annotations">annotation</a> types, default attributes are defined by using the
<code class="language-plaintext highlighter-rouge">default</code> keyword and will have corresponding default constant values initialized if not set.</p>
<p>Default attributes work well with Java 8’s default methods in interfaces, but attributes should be annotated with <code class="language-plaintext highlighter-rouge">@Default</code>:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">interface</span> <span class="nc">Val</span> <span class="o">{</span>
<span class="kt">int</span> <span class="nf">anAttribute</span><span class="o">();</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Default</span> <span class="k">default</span> <span class="kt">int</span> <span class="nf">otherAttribute</span><span class="o">()</span> <span class="o">{</span>
<span class="k">return</span> <span class="mi">0</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>
<p>Since version <code class="language-plaintext highlighter-rouge">2.0.15</code>, the <code class="language-plaintext highlighter-rouge">defaultAsDefault</code> style parameter (<code class="language-plaintext highlighter-rouge">@Value.Style(defaultAsDefault = true, ...)</code>) is supported.
This instructs generated builders to treat Java 8 default methods in interfaces as if they were annotated with <code class="language-plaintext highlighter-rouge">@Value.Default</code>.</p>
<p><a name="derived-attribute"></a></p>
<h3 id="derived-attributes">Derived attributes</h3>
<p>Derived attributes are attributes with values that are read from existing immutable instances, but
cannot be manually set.</p>
<p>To declare a derived attribute, create a non-abstract attribute initializer method and annotate it with
<code class="language-plaintext highlighter-rouge">org.immutables.value.Value.Derived</code>. In a similar manner to <a href="#default-attribute">default attributes</a>,
the body of the method should compute and return value of an attribute. Derived attributes act much like
regular methods that simply compute and return a value, but with a single important difference:
values of derived attributes are computed once and stored (at the end of object construction).</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">Order</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="nc">List</span><span class="o"><</span><span class="nc">Item</span><span class="o">></span> <span class="nf">items</span><span class="o">();</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Derived</span>
<span class="kd">public</span> <span class="kt">int</span> <span class="nf">totalCount</span><span class="o">()</span> <span class="o">{</span>
<span class="kt">int</span> <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>
<span class="k">for</span> <span class="o">(</span><span class="nc">Item</span> <span class="n">i</span> <span class="o">:</span> <span class="n">items</span><span class="o">())</span>
<span class="n">count</span> <span class="o">+=</span> <span class="n">i</span><span class="o">.</span><span class="na">count</span><span class="o">();</span>
<span class="k">return</span> <span class="n">count</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="nc">Order</span> <span class="n">order</span> <span class="o">=</span> <span class="nc">ImmutableOrder</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">addItems</span><span class="o">(</span><span class="nc">Item</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="s">"item1"</span><span class="o">,</span> <span class="mi">11</span><span class="o">))</span>
<span class="o">.</span><span class="na">addItems</span><span class="o">(</span><span class="nc">Item</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="s">"item2"</span><span class="o">,</span> <span class="mi">22</span><span class="o">))</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
<span class="c1">// total count will be already computed</span>
<span class="kt">int</span> <span class="n">totalCount33</span> <span class="o">=</span> <span class="n">order</span><span class="o">.</span><span class="na">totalCount</span><span class="o">();</span>
</code></pre></div></div>
<p>As with <a href="#default-attribute">default attributes</a>, derived attribute initializer
method bodies can refer to other default or derived attributes as long as there are no cycles.
If a cycle is detected during object construction, then an <code class="language-plaintext highlighter-rouge">IllegalStateException</code> will be thrown pointing
to the attribute names which form the cycle.</p>
<p><a name="nullable"></a></p>
<h3 id="nullable-attributes">Nullable attributes</h3>
<p>The use of nullable attributes is discouraged. If nullable attributes are really needed, add
a <code class="language-plaintext highlighter-rouge">@Nullable</code> annotation to the abstract attribute accessor. Any annotation with simple name
<code class="language-plaintext highlighter-rouge">Nullable</code> will work. Nullable attributes are not required to be set using a builder, and <code class="language-plaintext highlighter-rouge">null</code>
values are permitted to initialize them. Nullable collections and other special types are
not supported. More precisely, adding <code class="language-plaintext highlighter-rouge">@Nullable</code> turns an attribute into a “nothing-special”
attribute.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">interface</span> <span class="nc">NullAccepted</span> <span class="o">{</span>
<span class="nd">@Nullable</span> <span class="nc">Integer</span> <span class="nf">i1</span><span class="o">();</span>
<span class="nd">@Nullable</span> <span class="nc">Long</span> <span class="nf">l2</span><span class="o">();</span>
<span class="o">}</span>
<span class="nc">NullAccepted</span> <span class="n">obj</span> <span class="o">=</span> <span class="nc">ImmutableNullAccepted</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">i1</span><span class="o">(</span><span class="kc">null</span><span class="o">)</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
<span class="n">obj</span><span class="o">.</span><span class="na">toString</span><span class="o">();</span> <span class="c1">// NullAccepted{i1=null, l2=null}</span>
</code></pre></div></div>
<h4 id="nulls-in-collection">Nulls in collection</h4>
<p>As already mentioned, neither collection, nor its elements are supposed to be <code class="language-plaintext highlighter-rouge">null</code>. But for the reason of compatibility with the third party libraries or services you may need to allow or to skip (i.e. throw away silently) nulls. Collection attributes could be marked as <a href="#nullable">@Nullable</a>, but what about collection elements? In this case you can mark attribute with special annotations: <code class="language-plaintext highlighter-rouge">@AllowNulls</code> or <code class="language-plaintext highlighter-rouge">@SkipNulls</code>. These annotations are not supplied by <em>Immutables</em> and any annotations matching by a simple name will take effect — we call this approach BYOA (Bring Your Own Annotations). Please note, that Guava immutable collections do not support nulls, so this feature is only enabled when JDK collections are used, i.e. when Guava not available or <code class="language-plaintext highlighter-rouge">@Style(jdkOnly = true)</code>.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Style</span><span class="o">(</span><span class="n">jdkOnly</span> <span class="o">=</span> <span class="kc">true</span><span class="o">)</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">NullElements</span> <span class="o">{</span>
<span class="c1">// collection elements</span>
<span class="nd">@AllowNulls</span> <span class="nc">List</span><span class="o"><</span><span class="nc">Void</span><span class="o">></span> <span class="nf">al</span><span class="o">();</span>
<span class="nd">@SkipNulls</span> <span class="nc">List</span><span class="o"><</span><span class="nc">String</span><span class="o">></span> <span class="nf">sk</span><span class="o">();</span>
<span class="c1">// map values (but not keys)</span>
<span class="nd">@AllowNulls</span> <span class="nc">Map</span><span class="o"><</span><span class="nc">String</span><span class="o">,</span> <span class="nc">Integer</span><span class="o">></span> <span class="nf">bl</span><span class="o">();</span>
<span class="nd">@SkipNulls</span> <span class="nc">Map</span><span class="o"><</span><span class="nc">String</span><span class="o">,</span> <span class="nc">Integer</span><span class="o">></span> <span class="nf">sm</span><span class="o">();</span>
<span class="o">}</span>
</code></pre></div></div>
<p>It is also possible to use <code class="language-plaintext highlighter-rouge">@Nullable</code>, <code class="language-plaintext highlighter-rouge">@AllowNulls</code>, <code class="language-plaintext highlighter-rouge">@SkipNulls</code> as Java 8 type annotation, like <code class="language-plaintext highlighter-rouge">List<@Nullable Obj></code>, but it may not work depending on compiler (works in <em>ECJ</em> and <em>ErrorProne</em>, but not in plain <em>Javac</em>).</p>
<p><a name="lazy-attribute"></a></p>
<h3 id="lazy-attributes">Lazy attributes</h3>
<p>A lazy attribute is an initializer method that computes a value lazily and only once.</p>
<p>To declare a lazy attribute, create a non-abstract attribute initializer method and annotate it with
<code class="language-plaintext highlighter-rouge">org.immutables.value.Value.Lazy</code>. Similar to <a href="#derived-attribute">derived attributes</a>,
the body of the method should compute and return a value of an attribute.
Lazy attributes act much like regular methods, but compute values the first time they are
accessed and return the same memoized value on subsequent accesses.</p>
<p><strong>Things to be aware of</strong></p>
<ul>
<li>Lazy attributes are not included in <code class="language-plaintext highlighter-rouge">equals</code> and <code class="language-plaintext highlighter-rouge">hashCode</code> implementations! They are implicitly <a href="#auxiliary">auxiliary</a></li>
</ul>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">Order</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="nc">List</span><span class="o"><</span><span class="nc">Item</span><span class="o">></span> <span class="nf">items</span><span class="o">();</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Lazy</span>
<span class="kd">public</span> <span class="kt">int</span> <span class="nf">totalCost</span><span class="o">()</span> <span class="o">{</span>
<span class="kt">int</span> <span class="n">cost</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>
<span class="k">for</span> <span class="o">(</span><span class="nc">Item</span> <span class="n">i</span> <span class="o">:</span> <span class="n">items</span><span class="o">())</span>
<span class="n">cost</span> <span class="o">+=</span> <span class="n">i</span><span class="o">.</span><span class="na">count</span><span class="o">()</span> <span class="o">*</span> <span class="n">i</span><span class="o">.</span><span class="na">price</span><span class="o">();</span>
<span class="k">return</span> <span class="n">cost</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="nc">Order</span> <span class="n">order</span> <span class="o">=</span> <span class="nc">ImmutableOrder</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">addItems</span><span class="o">(</span><span class="nc">Item</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="s">"item1"</span><span class="o">,</span> <span class="mi">11</span><span class="o">,</span> <span class="mi">1</span><span class="o">))</span>
<span class="o">.</span><span class="na">addItems</span><span class="o">(</span><span class="nc">Item</span><span class="o">.</span><span class="na">of</span><span class="o">(</span><span class="s">"item2"</span><span class="o">,</span> <span class="mi">22</span><span class="o">,</span> <span class="mi">2</span><span class="o">))</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
<span class="c1">// total cost will be computed now</span>
<span class="kt">int</span> <span class="n">lazilyComputedCost</span> <span class="o">=</span> <span class="n">order</span><span class="o">.</span><span class="na">totalCost</span><span class="o">();</span>
<span class="c1">// total cost is already computed and stored value is returned</span>
<span class="n">lazilyComputedCost</span> <span class="o">=</span> <span class="n">order</span><span class="o">.</span><span class="na">totalCost</span><span class="o">();</span>
</code></pre></div></div>
<p>Lazy values are thread-safe and will be computed once and only once, regardless of race conditions.</p>
<p>Unlike <a href="#default-attribute">default</a> or <a href="#derived-attributes">derived</a> attributes,
body of the lazy attribute accessor method could refer to any attribute. If you call lazy attribute during initialization of a <a href="#default-attribute">default</a> or a <a href="#derived-attributes">derived</a> attribute, it will be initialized eagerly, making it an equivalent of a derived attribute.</p>
<p>Current implementation of lazy attributes is very similar to the way they were implemented in older versions of Scala.
Currently, this implementation strategy potentially suffers from the problem described in <a href="http://docs.scala-lang.org/sips/pending/improved-lazy-val-initialization.html">Scala SIP-20</a>.
On the other hand, problems can only occur if you are mixing immutable objects with
mutable/static/thread-local state: cyclic dependencies need to be introduced between different
immutable objects.</p>
<p><a name="check-method"></a></p>
<h3 id="precondition-check-method">Precondition check method</h3>
<p>One of the core advantages of immutable objects is the fact that an immutable object is
constructed with proper attribute values in a <em>consistent state</em>, and <em>never changes</em> afterwards.
Sometimes, however, a need arises to check attribute values or a combination of attribute values
for correctness (cross validation).</p>
<p>Normally, these checks would be written in the constructor of a hand-written class. However,
given that there is no hand-written constructor in an immutable implementation class, it is
necessary to specify these checks elsewhere. A non-private method annotated with <code class="language-plaintext highlighter-rouge">@Value.Check</code>
can be used to specify preconditions for generated classes:</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">NumberContainer</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="nc">List</span><span class="o"><</span><span class="nc">Number</span><span class="o">></span> <span class="nf">nonEmptyNumbers</span><span class="o">();</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Check</span>
<span class="kd">protected</span> <span class="kt">void</span> <span class="nf">check</span><span class="o">()</span> <span class="o">{</span>
<span class="nc">Preconditions</span><span class="o">.</span><span class="na">checkState</span><span class="o">(!</span><span class="n">nonEmptyNumbers</span><span class="o">().</span><span class="na">isEmpty</span><span class="o">(),</span>
<span class="s">"'nonEmptyNumbers' should have at least one number"</span><span class="o">);</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="o">...</span>
<span class="c1">// will throw IllegalStateException("'nonEmptyNumbers' should have at least one number")</span>
<span class="nc">ImmutableNumberContainer</span><span class="o">.</span><span class="na">builder</span><span class="o">().</span><span class="na">build</span><span class="o">();</span>
</code></pre></div></div>
<p>However, one should note how this differs from other kinds of object state validation where
objects may be constructed with values and later validated for correctness regarding business
rules in some context: Precondition checking should not be used to validate against such rules,
but should be used to preserve consistency and guarantee that the instances are usable.</p>
<p>Precondition check methods are executed when immutable objects are <em>instantiated and all attributes are initialized</em>, but <em>before being returned to a caller</em>. Any instance that fails the precondition checks is made unreachable to a caller due to an exception being raised.</p>
<h4 id="normalization">Normalization</h4>
<p>There’s additional variant of using <code class="language-plaintext highlighter-rouge">@Value.Check</code> annotation to compute normalized value. If you declare return type of validation method with the return type specified as abstract value type, this validation method will also be able to return substitute “normalized” instance. Normalized instance should always be of the immutable implementations type, otherwise <code class="language-plaintext highlighter-rouge">ClassCastException</code> will occur during construction.</p>
<p><em>Be warned that it’s easy to introduce unresolvable recursion, if normalization is implemented without proper checks or with conflicting checks. Always return <code class="language-plaintext highlighter-rouge">this</code> if a value do not require normalization.</em></p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">Normalized</span> <span class="o">{</span>
<span class="kt">int</span> <span class="nf">value</span><span class="o">();</span>
<span class="nd">@Value</span><span class="o">.</span><span class="na">Check</span>
<span class="k">default</span> <span class="nc">Normalized</span> <span class="nf">normalize</span><span class="o">()</span> <span class="o">{</span>
<span class="k">if</span> <span class="o">(</span><span class="n">value</span><span class="o">()</span> <span class="o">==</span> <span class="nc">Integer</span><span class="o">.</span><span class="na">MIN_VALUE</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="nc">ImmutableNormalized</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">value</span><span class="o">(</span><span class="mi">0</span><span class="o">)</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
<span class="o">}</span>
<span class="k">if</span> <span class="o">(</span><span class="n">value</span><span class="o">()</span> <span class="o"><</span> <span class="mi">0</span><span class="o">)</span> <span class="o">{</span>
<span class="k">return</span> <span class="nc">ImmutableNormalized</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">value</span><span class="o">(-</span><span class="n">value</span><span class="o">())</span>
<span class="o">.</span><span class="na">build</span><span class="o">();</span>
<span class="o">}</span>
<span class="k">return</span> <span class="k">this</span><span class="o">;</span>
<span class="o">}</span>
<span class="o">}</span>
<span class="kt">int</span> <span class="n">shouldBePositive2</span> <span class="o">=</span> <span class="nc">ImmutableNormalized</span><span class="o">.</span><span class="na">builder</span><span class="o">()</span>
<span class="o">.</span><span class="na">value</span><span class="o">(-</span><span class="mi">2</span><span class="o">)</span>
<span class="o">.</span><span class="na">build</span><span class="o">()</span>
<span class="o">.</span><span class="na">value</span><span class="o">();</span>
</code></pre></div></div>
<p><a name="copy-methods"></a></p>
<h3 id="copy-methods">Copy methods</h3>
<p><code class="language-plaintext highlighter-rouge">with*</code> methods (withers) allow to modify values of attributes by returning a new
immutable object with new value applied and the rest of attributes unchanged.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">counter</span> <span class="o">=</span> <span class="n">counter</span><span class="o">.</span><span class="na">withValue</span><span class="o">(</span><span class="n">counter</span><span class="o">.</span><span class="na">value</span><span class="o">()</span> <span class="o">+</span> <span class="mi">1</span><span class="o">)</span>
</code></pre></div></div>
<p>A cheap reference equality <code class="language-plaintext highlighter-rouge">==</code> check is added to prevent a copy of the same value by returning <code class="language-plaintext highlighter-rouge">this</code>.
Primitives are compared using the <code class="language-plaintext highlighter-rouge">==</code> value check. Primitive <code class="language-plaintext highlighter-rouge">float</code> and <code class="language-plaintext highlighter-rouge">double</code> are compared strictly by using <code class="language-plaintext highlighter-rouge">Float.floatToIntBits</code> and <code class="language-plaintext highlighter-rouge">Double.doubleToLongBits</code> respectively, consistently with how <code class="language-plaintext highlighter-rouge">Float.equals</code> and <code class="language-plaintext highlighter-rouge">Double.equals</code> work.
For strings and primitive wrapper types we use <code class="language-plaintext highlighter-rouge">Object.equals</code> equality. But in general, full equality checks were omitted: in practice it may be less computationally expensive to create new copy of a value than to check some attribute for deep-equality.</p>
<p>Wither methods are implemented to copy with structural sharing. It is useful to change one attribute value, but have other attributes values reference the same values as before, including any immutable collections and nested values that are wasteful to rebuild. New values will effectively
share the subgraphs of old values, which is desirable in many cases.</p>
<p>While it was tempting to generated a bunch of methods to support collections and maps such as
<code class="language-plaintext highlighter-rouge">withItemAdded</code> or <code class="language-plaintext highlighter-rouge">withKeyValuePut</code>, they might require a lot of variation like <em>add last</em> or
<em>add first</em> and will hide the fact that immutable collections are being rebuilt and/or rehashed, which is not always desirable for immutable collections. As of now, there’s only simple value replacement for all kinds of attributes. New collection values are guaranteed to be copied as immutable unless already immutable.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">Value</span> <span class="n">changedValue</span> <span class="o">=</span>
<span class="nc">ImmutableValue</span><span class="o">.</span><span class="na">copyOf</span><span class="o">(</span><span class="n">existingValue</span><span class="o">)</span>
<span class="o">.</span><span class="na">withName</span><span class="o">(</span><span class="s">"Changed Name"</span><span class="o">)</span>
<span class="o">.</span><span class="na">withValues</span><span class="o">(</span><span class="nc">Arrays</span><span class="o">.</span><span class="na">asList</span><span class="o">(</span><span class="s">"Only new value"</span><span class="o">))</span> <span class="c1">// replacing any copied collection</span>
</code></pre></div></div>
<p>Copy methods are generated by default, and to use them you need obtain a reference to an
immutable implementation class instance, rather than an up-casted abstract value type reference.</p>
<p>Setting the <code class="language-plaintext highlighter-rouge">@Value.Immutable(copy = false)</code> annotation parameter will <em>disable</em> the generation
of copy methods.</p>
<p><a name="singleton"></a></p>
<h3 id="singleton-instances">Singleton instances</h3>
<p>It is easy to create “empty” or “default” instances that will be singletons.
Use the <code class="language-plaintext highlighter-rouge">@Value.Immutable(singleton = true)</code> annotation parameter to generate singleton instances.
Use the concise <code class="language-plaintext highlighter-rouge">of()</code> factory method to obtain a singleton instance.</p>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span><span class="o">(</span><span class="n">singleton</span> <span class="o">=</span> <span class="kc">true</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">Data</span> <span class="o">{</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="nc">Set</span><span class="o"><</span><span class="nc">String</span><span class="o">></span> <span class="nf">chunks</span><span class="o">();</span>
<span class="o">}</span>
<span class="o">...</span>
<span class="kt">boolean</span> <span class="n">willBeTrue</span> <span class="o">=</span>
<span class="nc">ImmutableData</span><span class="o">.</span><span class="na">of</span><span class="o">()</span> <span class="o">==</span> <span class="nc">ImmutableData</span><span class="o">.</span><span class="na">of</span><span class="o">();</span>
<span class="c1">// true</span>
<span class="kt">boolean</span> <span class="n">willBeTrueAlso</span> <span class="o">=</span>
<span class="nc">ImmutableData</span><span class="o">.</span><span class="na">of</span><span class="o">().</span><span class="na">chunks</span><span class="o">().</span><span class="na">isEmpty</span><span class="o">();</span>
<span class="c1">// true</span>
</code></pre></div></div>
<p>The abstract value type of a singleton should not have any mandatory attributes, otherwise the
generation of singletons will not be possible.
You can make attributes non-mandatory by using <a href="#default-attribute">default</a> or <a href="#optional">optional</a> attributes.</p>
<p>As it stands, empty singleton instances can be combined with builders and constructors as long
as all attributes are non-mandatory. If you only want to provide a singleton instance, disable
builders and constructors:</p>
<ul>
<li>Use <code class="language-plaintext highlighter-rouge">singleton = true</code> and <code class="language-plaintext highlighter-rouge">builder = false</code> with <code class="language-plaintext highlighter-rouge">@Value.Immutable</code> annotations</li>
<li>Avoid the use of <code class="language-plaintext highlighter-rouge">@Value.Parameter</code>, to avoid generating constructors</li>
</ul>
<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nd">@Value</span><span class="o">.</span><span class="na">Immutable</span><span class="o">(</span><span class="n">singleton</span> <span class="o">=</span> <span class="kc">true</span><span class="o">,</span> <span class="n">builder</span> <span class="o">=</span> <span class="kc">false</span><span class="o">)</span>
<span class="kd">public</span> <span class="kd">abstract</span> <span class="kd">class</span> <span class="nc">Singleton</span> <span class="o">{</span>
<span class="c1">// Limit constructor accessibility to a package if needed.</span>
<span class="c1">// Private access will not work as ImmutableSingleton should</span>
<span class="c1">// be able to extend Singleton</span>
<span class="nc">Singleton</span><span class="o">()</span> <span class="o">{}</span>
<span class="o">}</span>
<span class="o">...</span>
<span class="nc">Singleton</span> <span class="n">singleInstance</span> <span class="o">=</span> <span class="nc">ImmutableSingleton</span><span class="o">.</span><span class="na">of</span><span class="o">();</span>
</code></pre></div></div>
<p><strong>Things to be aware of</strong></p>
<ul>
<li>If an abstract value type contains mandatory attributes but the generation of a singleton is requested:
<ul>
<li>Compilation error: could not generate default value for mandatory field.</li>
</ul>
</li>
</ul>
<p><a name="interning"></a></p>
<h3 id="instance-interning">Instance interning</h3>
<p>There are cases where a number of values of a given type are expected to be finite and
measurable performance improvements may be gained by interning those instances.</p>
<p>If all you need is to <em>strongly</em> intern all instances of particular value type — <em>Immutables</em> can do that for you.
Use the <code class="language-plaintext highlighter-rouge">@Value.Immutable(intern = true)</code> annotation parameter to enable strong interning:</p>
<ul>
<li>Any object returned by a builder or constructor will be interned and a “canonical” instance returned</li>
<li><code class="language-plaintext highlighter-rouge">equals</code> will be short-circuited to object reference equality.</li>
</ul>
<p><em>Strong</em> interning is supported by default and since version <code class="language-plaintext highlighter-rouge">2.6.0</code> <em>weak</em> interning is also supported via <code class="language-plaintext highlighter-rouge">@Value.Style(weakInterning = true)</code>.</p>
<p>Any other forms of interning including partial range interning
were left out to be implemented externally. There is, however, a module <code class="language-plaintext highlighter-rouge">org.immutables:ordinal</code>
which supports sophisticated domain-based interning of enum-like objects. See the documentation of
classes in that module.</p>
<p><a name="prehashed"></a></p>
<h3 id="precomputed-hashcode">Precomputed hashCode</h3>
<p>If an immutable class has a lot of attributes, or attributes may contain reasonably large
object graphs, then it may become inefficient to recompute <code class="language-plaintext highlighter-rouge">hashCode</code> value again and again
(when inserting instances into a <code class="language-plaintext highlighter-rouge">HashMap</code>, for example).</p>
<p>For such cases, hash codes can be precomputed on construction and stored for fast retrieval.
Just use the <code class="language-plaintext highlighter-rouge">@Value.Immutable(prehash = true)</code> annotation parameter to precompute hash values in advance.</p>
<p><a name="lazyhash"></a></p>
<h3 id="lazy-computation-of-hashcode">Lazy computation of hashCode</h3>
<p>Similarly to <a href="#prehashed">prehashed</a> hash codes, one can configure immutables to calculate hash code lazily.
Hash value will be computed (and cached) on first call to <code class="language-plaintext highlighter-rouge">hashCode()</code> method. The approach is
similar to <code class="language-plaintext highlighter-rouge">hashCode()</code> function in String class (also called <em>racy single check</em> in Effective Java book).