-
Notifications
You must be signed in to change notification settings - Fork 32
/
index.html
2560 lines (2440 loc) · 195 KB
/
index.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 lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="generator" content="Asciidoctor 0.1.4">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scala’s Types of Types</title>
<link rel="stylesheet" href="stylesheets/foundation.css">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/3.2.1/css/font-awesome.min.css">
<link rel="stylesheet" href="stylesheets/asciidoctor-pygments.css">
</head>
<body class="article toc2 toc-right">
<div id="header">
<h1>Scala’s Types of Types</h1>
<div id="toc" class="toc2">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#the-different-types-of-types-in-scala">1. The different types of… Types in Scala</a></li>
<li><a href="#work-in-progress">2. WORK IN PROGRESS</a></li>
<li><a href="#type-ascription">3. Type Ascription</a></li>
<li><a href="#unified-type-system-any-anyref-anyval">4. Unified Type System - Any, AnyRef, AnyVal</a></li>
<li><a href="#the-bottom-types-nothing-and-null">5. The Bottom Types - Nothing and Null</a></li>
<li><a href="#type-of-an-code-object-code">6. Type of an <code>object</code></a></li>
<li><a href="#type-variance-in-scala">7. Type Variance in Scala</a></li>
<li>
<ul class="sectlevel2">
<li><a href="#traits-as-in-interfaces-with-implementation">7.1. Traits, as in "interfaces with implementation"</a></li>
<li><a href="#type-linearization-vs-the-diamond-problem">7.2. Type Linearization vs. The Diamond Problem</a></li>
</ul>
</li>
<li><a href="#refined-types-refinements">8. Refined Types (refinements)</a></li>
<li><a href="#package-object">9. Package Object</a></li>
<li><a href="#type-alias">10. Type Alias</a></li>
<li><a href="#abstract-type-member">11. Abstract Type Member</a></li>
<li><a href="#self-recursive-type">12. Self-Recursive Type</a></li>
<li>
<ul class="sectlevel2">
<li><a href="#f-bounded-type">12.1. F-Bounded Type</a></li>
</ul>
</li>
<li><a href="#type-constructor-span-style-color-red-span">13. Type Constructor <span style="color:red">✗</span></a></li>
<li><a href="#higher-order-kind-span-style-color-red-span">14. Higher-Order Kind <span style="color:red">✗</span></a></li>
<li><a href="#case-class">15. Case Class</a></li>
<li><a href="#enumeration">16. Enumeration</a></li>
<li>
<ul class="sectlevel2">
<li><a href="#enumeration-2">16.1. Enumeration</a></li>
<li><a href="#enum">16.2. @enum</a></li>
</ul>
</li>
<li><a href="#value-class">17. Value Class</a></li>
<li><a href="#type-class-span-style-color-red-span">18. Type Class <span style="color:red">✗</span></a></li>
<li><a href="#self-type-annotation">19. Self Type Annotation</a></li>
<li><a href="#phantom-type">20. Phantom Type</a></li>
<li><a href="#structural-type">21. Structural Type</a></li>
<li><a href="#path-dependent-type">22. Path Dependent Type</a></li>
<li><a href="#type-projection">23. Type Projection</a></li>
<li><a href="#specialized-types">24. Specialized Types</a></li>
<li>
<ul class="sectlevel2">
<li><a href="#specialized">24.1. @specialized</a></li>
<li><a href="#miniboxing-span-style-color-red-span">24.2. Miniboxing <span style="color:red">✗</span></a></li>
</ul>
</li>
<li><a href="#type-lambda-span-style-color-red-span">25. Type Lambda <span style="color:red">✗</span></a></li>
<li><a href="#union-type-span-style-color-red-span">26. Union Type <span style="color:red">✗</span></a></li>
<li><a href="#delayed-init">27. Delayed Init</a></li>
<li><a href="#dynamic-type">28. Dynamic Type</a></li>
<li>
<ul class="sectlevel2">
<li><a href="#applydynamic">28.1. applyDynamic</a></li>
<li><a href="#applydynamicnamed">28.2. applyDynamicNamed</a></li>
<li><a href="#selectdynamic">28.3. selectDynamic</a></li>
<li><a href="#updatedynamic">28.4. updateDynamic</a></li>
</ul>
</li>
<li><a href="#bibliography-and-kudos">29. Bibliography and Kudos</a></li>
<li>
<ul class="sectlevel2">
<li><a href="#reference-and-further-reading">29.1. Reference and further reading</a></li>
<li><a href="#thanks-and-kudos">29.2. Thanks and kudos</a></li>
<li><a href="#give-back-some-kudos">29.3. Give back some kudos!</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div id="content">
<div class="sect1">
<h2 id="the-different-types-of-types-in-scala"><a class="anchor" href="#the-different-types-of-types-in-scala"></a>1. The different types of… Types in Scala</h2>
<div class="sectionbody">
<div class="paragraph">
<p>This blog post came into being after a few discussions about Types in Scala after some of JavaOne’s parties in 2013. After those discussions I figured that many questions are often repeated by different people, during their learning of Scala. I though that we didn’t have a full list of all tricks what we can to with Types in Scala, so I decided to write such a list - giving real life examples why we’d need these types.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="work-in-progress"><a class="anchor" href="#work-in-progress"></a>2. WORK IN PROGRESS</h2>
<div class="sectionbody">
<div class="paragraph">
<p>While I’m working on this article since quite some time, there’s still MUCH to do!
For example Higher Kinds need a rewrite, there’s a lot of detail to be added in Self Type’s and lots and lots more. Check the todo file for more.</p>
</div>
<div class="paragraph">
<p>If you’d like to help, please do! I’ll welcome any pull request, or suggestion (well, I’d prefer pull requests ;-).</p>
</div>
<div class="paragraph">
<p>Also, if you see a section marked with "<span style="color:red">✗</span>" it means that it needs re-work or that it’s not complete in some way.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="type-ascription"><a class="anchor" href="#type-ascription"></a>3. Type Ascription</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Scala has Type Inference, which means that we can skip telling the Type of something each time in the source code,
and instead we just use `val`s or `def`s without "saying the type explicitly in the source". This being explicit about
the type of something, is called a Type Ascription (sometimes called a "Type Annotation", but this naming convention can easily cause confusion, and is <em>not</em> what is used in Scala’s spec).</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">trait</span> <span class="tok-nc">Thing</span>
<span class="tok-k">def</span> <span class="tok-n">getThing</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Thing</span> <span class="tok-o">{</span> <span class="tok-o">}</span>
<span class="tok-c1">// without Type Ascription, the type is infered to be `Thing`</span>
<span class="tok-k">val</span> <span class="tok-n">infered</span> <span class="tok-k">=</span> <span class="tok-n">getThing</span>
<span class="tok-c1">// with Type Ascription</span>
<span class="tok-k">val</span> <span class="tok-n">thing</span><span class="tok-k">:</span> <span class="tok-kt">Thing</span> <span class="tok-o">=</span> <span class="tok-n">getThing</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>In these situations, leaving out the Type Ascription is OK. Although you may decide to always ascribe return types of public methods (<strong>that’s very good idea!</strong>) in order to make the code more self-documenting.</p>
</div>
<div class="paragraph">
<p>In case of doubt you can refer to the below hint-questions to wether or not, include a Type Ascription.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Is it a parameter? <strong>Yes</strong>, you have to.</p>
</li>
<li>
<p>Is it a public method’s return value? <strong>Yes</strong>, for self-documenting code and control over exported types.</p>
</li>
<li>
<p>Is it a recursive or overloaded methods return value? <strong>Yes</strong>, you have to.</p>
</li>
<li>
<p>Do you need to return a more general interface than the inferencer would find? <strong>Yes</strong>, otherwise you’d expose your implementation details for example.</p>
</li>
<li>
<p>Else… No, don’t include a Type Ascription.</p>
</li>
<li>
<p>Related hint: Including Type Ascriptions speeds up compilation, also it’s generally nice to see the return type of a method.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>So we put Type Ascriptions after value names. Having this said, let’s jump into the next topics, where these types will become
more and more interesting.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="unified-type-system-any-anyref-anyval"><a class="anchor" href="#unified-type-system-any-anyref-anyval"></a>4. Unified Type System - Any, AnyRef, AnyVal</h2>
<div class="sectionbody">
<div class="paragraph">
<p>We refer to a Scala’s typesystem as being "unified" because there is a "Top Type", <code>Any</code>. <strong>This is different than Java</strong>, which has "special cases" in form of primitive types (<code>int</code>, <code>long</code>, <code>float</code>, <code>double</code>, <code>byte</code>, <code>char</code>, <code>short</code>, <code>boolean</code>), which do not extend Java’s "Almost-Top Type" - <code>java.lang.Object</code>.</p>
</div>
<div class="imageblock" style="text-align: center">
<div class="content">
<img src="assets/img/scala-types.png" alt="Scala's Unified Type System">
</div>
</div>
<div class="paragraph">
<p>Scala takes on the idea of having one common Top Type for all Types by introducing <code>Any</code>. <code>Any</code> is a supertype of both <code>AnyRef</code> and <code>AnyVal</code>.</p>
</div>
<div class="paragraph">
<p><code>AnyRef</code> is the "object world" of Java (and the JVM), it corresponds to <code>java.lang.Object</code>, and is the supertype of all objects. <code>AnyVal</code> on the other hand represents the "value world" of Java, such as <code>int</code> and other JVM primitives.</p>
</div>
<div class="paragraph">
<p>Thanks to this hierarchy, we’re able to define methods taking <code>Any</code> - thus being compatible with both <code>scala.Int</code> instances as well as <code>java.lang.String</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">class</span> <span class="tok-nc">Person</span>
<span class="tok-k">val</span> <span class="tok-n">allThings</span> <span class="tok-k">=</span> <span class="tok-nc">ArrayBuffer</span><span class="tok-o">[</span><span class="tok-kt">Any</span><span class="tok-o">]()</span>
<span class="tok-k">val</span> <span class="tok-n">myInt</span> <span class="tok-k">=</span> <span class="tok-mi">42</span> <span class="tok-c1">// Int, kept as low-level `int` during runtime</span>
<span class="tok-n">allThings</span> <span class="tok-o">+=</span> <span class="tok-n">myInt</span> <span class="tok-c1">// Int (extends AnyVal)</span>
<span class="tok-c1">// has to be boxed (!) -> becomes java.lang.Integer in the collection (!)</span>
<span class="tok-n">allThings</span> <span class="tok-o">+=</span> <span class="tok-k">new</span> <span class="tok-nc">Person</span><span class="tok-o">()</span> <span class="tok-c1">// Person (extends AnyRef), no magic here</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>For the Typesystem it’s transparent, though on the JVM level once we get into <code>ArrayBuffer[Any]</code> our Int instances will have to be packed into objects. Let’s investigate the above example’s by using the Scala REPL and it’s <code>:javap</code> command (which shows the generated bytecode for our test class):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="asciidoc language-asciidoc">35: invokevirtual #47 // Method myInt:()I
38: invokestatic #53 // Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
41: invokevirtual #57 // Method scala/collection/mutable/ArrayBuffer.$plus$eq:(Ljava/lang/Object;)Lscala/collection/mutable/ArrayBuffer;</code></pre>
</div>
</div>
<div class="paragraph">
<p>You’ll notive that <code>myInt</code> is still carrying the value of a <code>int primitive</code> (this is visible as <code>I</code> at the end of the <code>myInt:()I</code> <strong>invokevirtual</strong> call). Then, right before adding it to the ArrayBuffer, scalac inserted a call to <code>BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer</code> (a small hint for not frequent bytecode readers, the method it calls is: <code>public Integer boxToInteger(i: int)</code>). This way, by having a smart compiler and treating everything as an object in this common hierarchy we’re able to get away from the "but primitives are different" edge-cases, at least at the level of our Scala source code - the compiler takes care of it for us. On JVM level, the distinction is still there of course, and scalac will do it’s best to keep using primitives wherever possible, as operations on them are faster, and take less memory (objects are obviously bigger than primitives).</p>
</div>
<div class="paragraph">
<p>On the other hand, we can limit a method to only be able to work on "lightweight" Value Types:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">def</span> <span class="tok-n">check</span><span class="tok-o">(</span><span class="tok-n">in</span><span class="tok-k">:</span> <span class="tok-kt">AnyVal</span><span class="tok-o">)</span> <span class="tok-k">=</span> <span class="tok-o">()</span>
<span class="tok-n">check</span><span class="tok-o">(</span><span class="tok-mi">42</span><span class="tok-o">)</span> <span class="tok-c1">// Int -> AnyVal</span>
<span class="tok-n">check</span><span class="tok-o">(</span><span class="tok-mf">13.37</span><span class="tok-o">)</span> <span class="tok-c1">// Double -> AnyVal</span>
<span class="tok-n">check</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">Object</span><span class="tok-o">)</span> <span class="tok-c1">// -> AnyRef = fails to compile</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>In the above example I’ve used a TypeClass <code>Checker[T]</code> and a type bound, which will be discussed below. The general idea is that this method will only take <a href="#value-class">Value Classes</a>, be it Int or our own Value Type. While probably not used very often, it shows how nicely the typesystem embraces java primitives, and brings them into the "real" type system, and not as a separate case, as is the case with Java.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="the-bottom-types-nothing-and-null"><a class="anchor" href="#the-bottom-types-nothing-and-null"></a>5. The Bottom Types - Nothing and Null</h2>
<div class="sectionbody">
<div class="paragraph">
<p>In Scala everything has "some" type… but have you ever wondered how the type inferencer can still work, and infer sound types when working with "weird" situations like throwing exceptions? Let’s investigate the below "if/else throw" example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">val</span> <span class="tok-n">thing</span><span class="tok-k">:</span> <span class="tok-kt">Int</span> <span class="tok-o">=</span>
<span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">test</span><span class="tok-o">)</span>
<span class="tok-mi">42</span> <span class="tok-c1">// : Int</span>
<span class="tok-k">else</span>
<span class="tok-k">throw</span> <span class="tok-k">new</span> <span class="tok-nc">Exception</span><span class="tok-o">(</span><span class="tok-s">"Whoops!"</span><span class="tok-o">)</span> <span class="tok-c1">// : Nothing</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>As you can see in the comments, the type of the if block is <code>Int</code> (easy), the type of the else block is <code>Nothing</code> (interesting). The inferencer was able to infer that the <code>thing</code> value, will only ever be of type <code>Int</code>. This is because of the <strong>Bottom Type</strong> property of Nothing.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="icon-note" title="Note"></i>
</td>
<td class="content">
A very nice intuition about how bottom types work is: <em>"<code>Nothing</code> extends everything."</em>
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Type inference always looks for the "common type" of both branches in an if stamement, so if the other branch here is a Type that extends everything, the infered type will automatically be the Type from the first branch.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-nc">Types</span> <span class="tok-n">visualized</span><span class="tok-k">:</span>
<span class="tok-err">[</span><span class="tok-kt">Int</span><span class="tok-err">]</span> <span class="tok-kt">-></span> <span class="tok-kt">...</span> <span class="tok-kt">-></span> <span class="tok-kt">AnyVal</span> <span class="tok-kt">-></span> <span class="tok-kt">Any</span>
<span class="tok-nc">Nothing</span> <span class="tok-o">-></span> <span class="tok-o">[</span><span class="tok-kt">Int</span><span class="tok-o">]</span> <span class="tok-o">-></span> <span class="tok-o">...</span> <span class="tok-o">-></span> <span class="tok-nc">AnyVal</span> <span class="tok-o">-></span> <span class="tok-nc">Any</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>The same reasoning can be applied to the second Bottom Type in Scala - <code>Null</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">val</span> <span class="tok-n">thing</span><span class="tok-k">:</span> <span class="tok-kt">String</span> <span class="tok-o">=</span>
<span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">test</span><span class="tok-o">)</span>
<span class="tok-s">"Yay!"</span> <span class="tok-c1">// : String</span>
<span class="tok-k">else</span>
<span class="tok-kc">null</span> <span class="tok-c1">// : Null</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>The type of <code>thing</code> is as expected, String. <code>Null</code> follows ALMOST the same rules as Nothing. I’ll use this case to take a small detour to talk about inference, and the differences between AnyVals and AnyRefs.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="asciidoc language-asciidoc">Types visualized:
[String] -> AnyRef -> Any
Null -> [String] -> AnyRef -> Any
infered type: String</code></pre>
</div>
</div>
<div class="paragraph">
<p>Let’s think about <code>Int</code> and other primitives, which cannot hold null values. To investigate this case let’s drop into the REPL and use the <code>:type</code> command (which allows to get the type of an expression):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala-repl language-scala-repl">scala> :type if (false) 23 else null
Any</code></pre>
</div>
</div>
<div class="paragraph">
<p>This is different than the case with a String object in one of the branches. Let’s look into the types in detail here, as <code>Null</code> is a bit less "extends everything" than <code>Nothing</code>. Let’s see what <code>Int</code> extends in detail, by using <code>:type</code> again on it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala-repl language-scala-repl">scala> :type -v 12
// Type signature
Int
// Internal Type structure
TypeRef(TypeSymbol(final abstract class Int extends AnyVal))</code></pre>
</div>
</div>
<div class="paragraph">
<p>The verbose option adds a bit more information here, now we know that <code>Int</code> is an <code>AnyVal</code> - this is a special class representing value types - which cannot hold <code>Null</code>. If we look into <a href="https://github.com/scala/scala/blob/v2.10.3/src/library/scala/AnyVal.scala">AnyVal’s sources</a>, we’ll find:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">abstract</span> <span class="tok-k">class</span> <span class="tok-nc">AnyVal</span> <span class="tok-k">extends</span> <span class="tok-nc">Any</span> <span class="tok-k">with</span> <span class="tok-nc">NotNull</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>I’m bringing this up here because the core functionality of AnyVal is so nicely represented using the Types here. <strong>Notice the <code>NotNull</code> trait!</strong></p>
</div>
<div class="paragraph">
<p>Coming back to the subject why the common Type for our if statement with an <code>AnyVal</code> on one code block and a <code>null</code> on the other one was Any and not something else. The one sentence way to define it is: <code>Null extends all AnyRefs</code> whereas <code>Nothing extends anything</code>. As AnyVals (such as numbers), are not in the same tree as AnyRefs, the only common Type between a number and a <code>null</code> value is Any - which explains our case.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-nc">Types</span> <span class="tok-n">visualized</span><span class="tok-k">:</span>
<span class="tok-kt">Int</span> <span class="tok-kt">-></span> <span class="tok-kt">NotNull</span> <span class="tok-kt">-></span> <span class="tok-kt">AnyVal</span> <span class="tok-kt">-></span> <span class="tok-o">[</span><span class="tok-kt">Any</span><span class="tok-o">]</span>
<span class="tok-nc">Null</span> <span class="tok-o">-></span> <span class="tok-nc">AnyRef</span> <span class="tok-o">-></span> <span class="tok-o">[</span><span class="tok-kt">Any</span><span class="tok-o">]</span>
<span class="tok-n">infered</span> <span class="tok-n">type</span><span class="tok-k">:</span> <span class="tok-kt">Any</span>
</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="type-of-an-code-object-code"><a class="anchor" href="#type-of-an-code-object-code"></a>6. Type of an <code>object</code></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Scala `object`s are implemented via classes (obviously - as it’s the basic building block on the JVM),
but you’ll notice that we cannot get its type the same way as we would with an simple class…</p>
</div>
<div class="paragraph">
<p>I would surprisingly often get the question on how to pass an object into a method. Just saying <code>obj: ExampleObj</code> won’t work
because that’s already referring to the instance, so there’s a member called <code>type</code> which should be used in such cases.</p>
</div>
<div class="paragraph">
<p>How it might look like in your code is explained by the below example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">object</span> <span class="tok-nc">ExampleObj</span>
<span class="tok-k">def</span> <span class="tok-n">takeAnObject</span><span class="tok-o">(</span><span class="tok-n">obj</span><span class="tok-k">:</span> <span class="tok-kt">ExampleObj.</span><span class="tok-k">type</span><span class="tok-o">)</span> <span class="tok-k">=</span> <span class="tok-o">{}</span>
<span class="tok-n">takeAnObject</span><span class="tok-o">(</span><span class="tok-nc">ExampleObj</span><span class="tok-o">)</span>
</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="type-variance-in-scala"><a class="anchor" href="#type-variance-in-scala"></a>7. Type Variance in Scala</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Variance, in general, can be explained as "type compatible-ness" between types, forming an <code>extends</code> relation.
The most popular cases where you’ll have to deal with this is when working with containers or functions (so… surprisingly often!).</p>
</div>
<div class="paragraph">
<p>A major difference from Java in Scala is, that container types are <strong>not-variant by default</strong>!
This means that if you have a container defined as <code>Box[A]</code>, and then use it with a <code>Fruit</code> in place
of the type parameter <code>A</code>, you will not be able to insert an <code>Apple</code> (which <em>IS-A</em> <code>Fruit</code>) into it.</p>
</div>
<div class="paragraph">
<p>Variance in Scala is defined by using <code>+</code> and <code>-</code> signs in front of type parameters.</p>
</div>
<div class="paragraph">
<p><a href="http://www.slideshare.net/dgalichet/demystifying-scala-type-system">http://www.slideshare.net/dgalichet/demystifying-scala-type-system</a></p>
</div>
<table class="tableblock frame-all grid-all" style="width:100%; ">
<colgroup>
<col style="width:33%;">
<col style="width:33%;">
<col style="width:33%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">Name</th>
<th class="tableblock halign-left valign-top">Description</th>
<th class="tableblock halign-left valign-top">Scala Syntax</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">Invariant</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">C[T'] and C[T] are <strong>not</strong> related</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">C[T]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">Covariant</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">C[T'] is a subclass of C[T]</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">C[+T]</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">Contravariant</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">C[T] is a subclass of C[T']</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">C[-T]</p></td>
</tr>
</tbody>
</table>
<div class="paragraph">
<p>The above table ilustrates all variance cases we’ll have to worry about - in an abstract way.
In case you’re wondering where you’d have to care about this - in fact, you’re exposed to this each time
you’re working with collections you’re being faced with the question "is it covariant?".</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="icon-note" title="Note"></i>
</td>
<td class="content">
Most <em>immutable</em> collections are <em>covariant</em>, and most <em>mutable</em> collections are <em>invariant</em>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>There are (at least) two nice and very intuitive examples of this in Scala. One being "any collection", where we’ll use a <code>List[+A]</code> as our example, and functions. When talking about <code>List</code> in Scala, we usually mean <code>scala.collection.immutable.List[+A]</code>, which is immutable as well as covariant, let’s look how this relates to building lists containing items of different types.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">class</span> <span class="tok-nc">Fruit</span>
<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">Apple</span><span class="tok-o">()</span> <span class="tok-k">extends</span> <span class="tok-nc">Fruit</span>
<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">Orange</span><span class="tok-o">()</span> <span class="tok-k">extends</span> <span class="tok-nc">Fruit</span>
<span class="tok-k">val</span> <span class="tok-n">l1</span><span class="tok-k">:</span> <span class="tok-kt">List</span><span class="tok-o">[</span><span class="tok-kt">Apple</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-nc">Apple</span><span class="tok-o">()</span> <span class="tok-o">::</span> <span class="tok-nc">Nil</span>
<span class="tok-k">val</span> <span class="tok-n">l2</span><span class="tok-k">:</span> <span class="tok-kt">List</span><span class="tok-o">[</span><span class="tok-kt">Fruit</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-nc">Orange</span><span class="tok-o">()</span> <span class="tok-o">::</span> <span class="tok-n">l1</span>
<span class="tok-c1">// and also, it's safe to prepend with "anything",</span>
<span class="tok-c1">// as we're building a new list - not modifying the previous instance</span>
<span class="tok-k">val</span> <span class="tok-n">l3</span><span class="tok-k">:</span> <span class="tok-kt">List</span><span class="tok-o">[</span><span class="tok-kt">AnyRef</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-s">""</span> <span class="tok-o">::</span> <span class="tok-n">l2</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>It’s worth mentioning that while <strong>having immutable collections co-variant is <em>safe</em></strong>, the same cannot be said about mutable collections. The classic example here is <code>Array[T]</code> which is <strong>invariant</strong>. Let’s look at what invariance means for us here, and how it saves us from mistakes:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-c1">// won't compile</span>
<span class="tok-k">val</span> <span class="tok-n">a</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">Any</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-nc">Array</span><span class="tok-o">[</span><span class="tok-kt">Int</span><span class="tok-o">](</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-mi">2</span><span class="tok-o">,</span> <span class="tok-mi">3</span><span class="tok-o">)</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>Such an assigment won’t compile, because of Array’s invariance. If this assignment would be valid, we’d run into the problem of being able to write such code: <code>a(0) = "" // ArrayStoreException!</code> which would fail with the dreaded <code>ArrayStoreException</code>.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="icon-tip" title="Tip"></i>
</td>
<td class="content">
We said that "most" immutable collections are covariant in scala. In case you’re curious, one example of an immutable collection which stands out from that, and is invariant, it’s <code>Set[A]</code>.
</td>
</tr>
</table>
</div>
<div class="sect2">
<h3 id="traits-as-in-interfaces-with-implementation"><a class="anchor" href="#traits-as-in-interfaces-with-implementation"></a>7.1. Traits, as in "interfaces with implementation"</h3>
<div class="paragraph">
<p>First, let’s take a look as the simplest thing possible about traits:
how we can basically treat a type with multiple traits mixed in, as if it is implementing these "interfaces with implementation",
as you might be tempted to call them if comming from Java-land:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">class</span> <span class="tok-nc">Base</span> <span class="tok-o">{</span> <span class="tok-k">def</span> <span class="tok-n">b</span> <span class="tok-k">=</span> <span class="tok-s">""</span> <span class="tok-o">}</span>
<span class="tok-k">trait</span> <span class="tok-nc">Cool</span> <span class="tok-o">{</span> <span class="tok-k">def</span> <span class="tok-n">c</span> <span class="tok-k">=</span> <span class="tok-s">""</span> <span class="tok-o">}</span>
<span class="tok-k">trait</span> <span class="tok-nc">Awesome</span> <span class="tok-o">{</span> <span class="tok-k">def</span> <span class="tok-n">a</span> <span class="tok-o">=</span><span class="tok-s">""</span> <span class="tok-o">}</span>
<span class="tok-k">class</span> <span class="tok-nc">BA</span> <span class="tok-k">extends</span> <span class="tok-nc">Base</span> <span class="tok-k">with</span> <span class="tok-nc">Awesome</span>
<span class="tok-k">class</span> <span class="tok-nc">BC</span> <span class="tok-k">extends</span> <span class="tok-nc">Base</span> <span class="tok-k">with</span> <span class="tok-nc">Cool</span>
<span class="tok-c1">// as you might expect, you can upcast these instances into any of the traits they've mixed-in</span>
<span class="tok-k">val</span> <span class="tok-n">ba</span><span class="tok-k">:</span> <span class="tok-kt">BA</span> <span class="tok-o">=</span> <span class="tok-k">new</span> <span class="tok-nc">BA</span>
<span class="tok-k">val</span> <span class="tok-n">bc</span><span class="tok-k">:</span> <span class="tok-kt">Base</span> <span class="tok-kt">with</span> <span class="tok-kt">Cool</span> <span class="tok-o">=</span> <span class="tok-k">new</span> <span class="tok-nc">BC</span>
<span class="tok-k">val</span> <span class="tok-n">b1</span><span class="tok-k">:</span> <span class="tok-kt">Base</span> <span class="tok-o">=</span> <span class="tok-n">ba</span>
<span class="tok-k">val</span> <span class="tok-n">b2</span><span class="tok-k">:</span> <span class="tok-kt">Base</span> <span class="tok-o">=</span> <span class="tok-n">bc</span>
<span class="tok-n">ba</span><span class="tok-o">.</span><span class="tok-n">a</span>
<span class="tok-n">bc</span><span class="tok-o">.</span><span class="tok-n">c</span>
<span class="tok-n">b1</span><span class="tok-o">.</span><span class="tok-n">b</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>So far this should have been relatively well known to you. Now let’s to into the world of the "diamond problem",
which people who know C++ might have been expecting. Basically "The Diamond Problem" is a situation during multiple inheritance
where we’re not sure to what we want to refer to. The below image ilustrates the problem, if you would think of traits as if they were
directly multiple inheritance:</p>
</div>
</div>
<div class="sect2">
<h3 id="type-linearization-vs-the-diamond-problem"><a class="anchor" href="#type-linearization-vs-the-diamond-problem"></a>7.2. Type Linearization vs. The Diamond Problem</h3>
<div class="imageblock" style="text-align: center">
<div class="content">
<img src="assets/img/220px-Diamond_inheritance.svg.png" alt="Diamond Inheritance">
</div>
</div>
<div class="paragraph">
<p>For the "diamond problem" to appear, it’s enough if we have one overriding implementation in <code>B</code> or/and <code>C</code>. This introduces an ambiguity when calling the common method in <code>D</code>, did we inherit the version of the method from <code>C</code> or from <code>B</code>? In Scala’s case the case with only one overriding method is very simple - the override wins. But let’s work through the more complex case:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>class <code>A</code> defines a method <code>common</code> returning <code>a</code>,</p>
</li>
<li>
<p>trait <code>B</code> DOES override <code>common</code> to return <code>b</code>,</p>
</li>
<li>
<p>trait <code>C</code> DOES override <code>common</code> to return <code>c</code>,</p>
</li>
<li>
<p>class <code>D</code> extends both <code>B</code> and <code>C</code>,</p>
</li>
<li>
<p>which version of the <code>common</code> method does class <code>D</code> inherit? The overriden impementation from <code>C</code>, or the one from <code>B</code>?</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>This ambiguity is a pain point of every multiple-inheritance-like mechanism. Scala solves this problem by so called <strong>Type Linearization</strong>.
In other words, given a diamond class hierarchy, we are <strong>always</strong> (and <strong>deterministically</strong>) able to determine what will be called when inside D we call <code>common</code>.
Let’s put this into code and then talk about linearization:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">trait</span> <span class="tok-nc">A</span> <span class="tok-o">{</span> <span class="tok-k">def</span> <span class="tok-n">common</span> <span class="tok-k">=</span> <span class="tok-s">"A"</span> <span class="tok-o">}</span>
<span class="tok-k">trait</span> <span class="tok-nc">B</span> <span class="tok-k">extends</span> <span class="tok-n">A</span> <span class="tok-o">{</span> <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">common</span> <span class="tok-k">=</span> <span class="tok-s">"B"</span> <span class="tok-o">}</span>
<span class="tok-k">trait</span> <span class="tok-nc">C</span> <span class="tok-k">extends</span> <span class="tok-n">A</span> <span class="tok-o">{</span> <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">common</span> <span class="tok-k">=</span> <span class="tok-s">"C"</span> <span class="tok-o">}</span>
<span class="tok-k">class</span> <span class="tok-nc">D1</span> <span class="tok-k">extends</span> <span class="tok-n">B</span> <span class="tok-k">with</span> <span class="tok-n">C</span>
<span class="tok-k">class</span> <span class="tok-nc">D2</span> <span class="tok-k">extends</span> <span class="tok-n">C</span> <span class="tok-k">with</span> <span class="tok-n">B</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>The results will be as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-n">D1</span><span class="tok-o">).</span><span class="tok-n">common</span> <span class="tok-o">==</span> <span class="tok-s">"C"</span>
<span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-n">D2</span><span class="tok-o">).</span><span class="tok-n">common</span> <span class="tok-o">==</span> <span class="tok-s">"B"</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>The reason for this is that Scala applied the type linearization for us here. The algorithm goes like this:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>start building a list of types, the first element is the type we’re linearizing right now,</p>
</li>
<li>
<p>expand each supertype recursively and put all their types into this list (it should be flat, not nested),</p>
</li>
<li>
<p>remove duplicates from the resulting list, by scanning it from the left, and removing a type that you’ve already "seen"</p>
</li>
<li>
<p>done.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Let’s apply this algorithm on our diamond example by hand, to verify why <code>D1 extends B with C</code> (and <code>D2 extends C with B</code>) yielded the results they did:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-c1">// start with D1:</span>
<span class="tok-n">B</span> <span class="tok-k">with</span> <span class="tok-n">C</span> <span class="tok-k">with</span> <span class="tok-o"><</span><span class="tok-n">D1</span><span class="tok-o">></span>
<span class="tok-c1">// expand all the types until you rach Any for all of them:</span>
<span class="tok-o">(</span><span class="tok-nc">Any</span> <span class="tok-k">with</span> <span class="tok-nc">AnyRef</span> <span class="tok-k">with</span> <span class="tok-n">A</span> <span class="tok-k">with</span> <span class="tok-n">B</span><span class="tok-o">)</span> <span class="tok-k">with</span> <span class="tok-o">(</span><span class="tok-nc">Any</span> <span class="tok-k">with</span> <span class="tok-nc">AnyRef</span> <span class="tok-k">with</span> <span class="tok-n">A</span> <span class="tok-k">with</span> <span class="tok-n">C</span><span class="tok-o">)</span> <span class="tok-k">with</span> <span class="tok-o"><</span><span class="tok-n">D1</span><span class="tok-o">></span>
<span class="tok-c1">// remove duplicates by removing "already seen" types, when moving left-to-right:</span>
<span class="tok-o">(</span><span class="tok-nc">Any</span> <span class="tok-k">with</span> <span class="tok-nc">AnyRef</span> <span class="tok-k">with</span> <span class="tok-n">A</span> <span class="tok-k">with</span> <span class="tok-n">B</span><span class="tok-o">)</span> <span class="tok-k">with</span> <span class="tok-o">(</span> <span class="tok-n">C</span><span class="tok-o">)</span> <span class="tok-k">with</span> <span class="tok-o"><</span><span class="tok-n">D1</span><span class="tok-o">></span>
<span class="tok-c1">// write the resulting type nicely:</span>
<span class="tok-nc">Any</span> <span class="tok-k">with</span> <span class="tok-nc">AnyRef</span> <span class="tok-k">with</span> <span class="tok-n">A</span> <span class="tok-k">with</span> <span class="tok-n">B</span> <span class="tok-k">with</span> <span class="tok-n">C</span> <span class="tok-k">with</span> <span class="tok-o"><</span><span class="tok-n">D1</span><span class="tok-o">></span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>So when calling the <code>common</code> method, it’s now very simple to decide which version we want to call: we simply look at the linearized type,
and try to resolve the method by going from the right in the resulting linearized type. In the case of <code>D1</code>, the "rightmost" trait providing an implementation of <code>common</code> is <code>C</code>, so it’s overriding the implementation provided by <code>B</code>. The result of calling <code>common</code> inside <code>D1</code> would be <code>"c"</code>.</p>
</div>
<div class="paragraph">
<p>You can wrap your head around this method by trying it out on the <code>D2</code> class - it should linearize with <code>B</code> after <code>C</code>, thus yielding a <code>"b"</code> if you’d run the code.
Also it’s rather easy to resolve the simpler cases of linearization by just thinking "rightmost wins", but this is quite a simplification which, while helpful, does not give the full picture about the algorithm.</p>
</div>
<div class="paragraph">
<p>It is worth mentioning that using this technique we also know <strong>"who is my <code>super</code>?"</strong>. It’s as easy as "looking left" in the linearized type, from wherever class you want to check who your superclass is. So for example in our case (<code>D1</code>), the superclass of <code>C</code> is <code>B</code>.</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="refined-types-refinements"><a class="anchor" href="#refined-types-refinements"></a>8. Refined Types (refinements)</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Refinements are very easy to explain as "subclassing without naming the subclass". So in source code it would look like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">class</span> <span class="tok-nc">Entity</span>
<span class="tok-k">trait</span> <span class="tok-nc">Persister</span> <span class="tok-o">{</span>
<span class="tok-k">def</span> <span class="tok-n">doPersist</span><span class="tok-o">(</span><span class="tok-n">e</span><span class="tok-k">:</span> <span class="tok-kt">Entity</span><span class="tok-o">)</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
<span class="tok-n">e</span><span class="tok-o">.</span><span class="tok-n">persistForReal</span><span class="tok-o">()</span>
<span class="tok-o">}</span>
<span class="tok-o">}</span>
<span class="tok-c1">// our refined instance (and type):</span>
<span class="tok-k">val</span> <span class="tok-n">refinedMockPersister</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Persister</span> <span class="tok-o">{</span>
<span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">doPersist</span><span class="tok-o">(</span><span class="tok-n">e</span><span class="tok-k">:</span> <span class="tok-kt">Entity</span><span class="tok-o">)</span> <span class="tok-k">=</span> <span class="tok-o">()</span>
<span class="tok-o">}</span>
</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="package-object"><a class="anchor" href="#package-object"></a>9. Package Object</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Package Objects have been added to Scala in 2.8 <a href="#package-object">Package Object</a> and do not really extend the type system as such,
but they provide an pretty useful pattern for "importing a bunch of stuff together" as well as being one of the places
the compiler will look for implicit values.</p>
</div>
<div class="paragraph">
<p>Declaring a package object is as simple as using the keywords <code>package</code> and <code>object</code> in conjunction, such as:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="asciidoc language-asciidoc">// src/main/scala/com/garden/apples/package.scala
package com.garden
package object apples extends RedApples with GreenApples {
val redApples = List(red1, red2)
val greenApples = List(green1, green2)
}
trait RedApples {
val red1, red2 = "red"
}
trait GreenApples {
val green1, green2 = "green"
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>It’s a custom to put package object’s in a file called <code>package.scala</code> into the package they’re the object for. Investigate the above example’s
source path and package to see what that means.</p>
</div>
<div class="paragraph">
<p>On the usage side, you get the real gains, because when you import "the package", you import any state that is defined in the package side along with it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">import</span> <span class="tok-nn">com.garden.apples._</span>
<span class="tok-n">redApples</span> <span class="tok-n">foreach</span> <span class="tok-n">println</span>
</code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="type-alias"><a class="anchor" href="#type-alias"></a>10. Type Alias</h2>
<div class="sectionbody">
<div class="paragraph">
<p>It’s not really another kind of type, but a trick we can use to make our code more readable:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">type</span> <span class="tok-kt">User</span> <span class="tok-o">=</span> <span class="tok-nc">String</span>
<span class="tok-k">type</span> <span class="tok-kt">Age</span> <span class="tok-o">=</span> <span class="tok-nc">Int</span>
<span class="tok-k">val</span> <span class="tok-n">data</span><span class="tok-k">:</span> <span class="tok-kt">Map</span><span class="tok-o">[</span><span class="tok-kt">User</span>, <span class="tok-kt">Age</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-nc">Map</span><span class="tok-o">.</span><span class="tok-n">empty</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>Using this trick the Map definition now suddenly "makes sense!". If we’d just used a <code>String => Int</code> map,
we’d make the code less readable. Here we can keep using our primitives (maybe we need this for performance etc),
but <strong>name them</strong> so it makes sense for the future reader of this class.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="icon-note" title="Note"></i>
</td>
<td class="content">
Note that when you create an alias for a class, you <strong>do not</strong> alias its companion object in tandem. For example,
assuming you’ve got <code>case class Person(name: String)</code> and an alias <code>type User = Person</code>, calling <code>User("John")</code> will
result in an <em>error</em>, as <code>Person("John")</code> (what we could expect to be effectively called here) implicitly invokes
<code>apply</code> method from <code>Person</code> companion object that is not aliased in this case.
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect1">
<h2 id="abstract-type-member"><a class="anchor" href="#abstract-type-member"></a>11. Abstract Type Member</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Let’s now go deeper into the use cases of Type Aliases, which we call Abstract Type Members.</p>
</div>
<div class="paragraph">
<p>With Abstract Type Members we say "I expect someone to tell me about some type - I’ll refer to it by the name MyType".
It’s most basic function is allowing us to define generic classes (templates), but instead of using the <code>class Clazz[A, B]</code> syntax, we name them inside the class, like this:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">trait</span> <span class="tok-nc">SimplestContainer</span> <span class="tok-o">{</span>
<span class="tok-k">type</span> <span class="tok-kt">A</span> <span class="tok-c1">// Abstract Type Member</span>
<span class="tok-k">def</span> <span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">A</span>
<span class="tok-o">}</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>Which for Java folks may seem very similar to the <code>Container<A></code> syntax at first, but it’s a bit more powerful as we’ll see in the section about <a href="#path-dependent-type">Path Dependent Types</a>, as well as in the below example.</p>
</div>
<div class="paragraph">
<p>It is important to notice that while in the naming contains the word "abstract", it does not behave exactly like an abstract field - so you can still create a new instance of <code>SimplestContainer</code> without "implementing" the type member <code>A</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">new</span> <span class="tok-nc">SimplestContainer</span> <span class="tok-c1">// valid, but A is "anything"</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>You might be wondering what type <code>A</code> was bound to, since we didn’t provide any information about it anywhere.
Turns out <code>type A</code> is actualy just a shorthand for <code>type A >: Nothing <: Any</code>, which means "anything".</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">object</span> <span class="tok-nc">IntContainer</span> <span class="tok-k">extends</span> <span class="tok-nc">SimplestContainer</span> <span class="tok-o">{</span>
<span class="tok-k">type</span> <span class="tok-kt">A</span> <span class="tok-o">=</span> <span class="tok-nc">Int</span>
<span class="tok-k">def</span> <span class="tok-n">value</span> <span class="tok-k">=</span> <span class="tok-mi">42</span>
<span class="tok-o">}</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>So we "provide the type" using a <a href="#type-alias">Type Alias</a>, and now we can implement the value method which returns an <code>Int</code>.</p>
</div>
<div class="paragraph">
<p>The more interesting uses of Abstract Type Members start when we apply constraints to them. For example imagine you want to have a container that can only store anything that is of a <code>Number</code> instance. Such constraint can be annotated on a type member right where we defined it first:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">trait</span> <span class="tok-nc">OnlyNumbersContainer</span> <span class="tok-o">{</span>
<span class="tok-k">type</span> <span class="tok-kt">A</span> <span class="tok-k"><:</span> <span class="tok-kt">Number</span>
<span class="tok-k">def</span> <span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">A</span>
<span class="tok-o">}</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or we can add constraints later on in the class hierarchy, for example by mixing in a trait that states "only Numbers":</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">trait</span> <span class="tok-nc">SimpleContainer</span> <span class="tok-o">{</span>
<span class="tok-k">type</span> <span class="tok-kt">A</span>
<span class="tok-k">def</span> <span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">A</span>
<span class="tok-o">}</span>
<span class="tok-k">trait</span> <span class="tok-nc">OnlyNumbers</span> <span class="tok-o">{</span>
<span class="tok-k">type</span> <span class="tok-kt">A</span> <span class="tok-k"><:</span> <span class="tok-kt">Number</span>
<span class="tok-o">}</span>
<span class="tok-k">val</span> <span class="tok-n">ints</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">SimpleContainer</span> <span class="tok-k">with</span> <span class="tok-nc">OnlyNumbers</span> <span class="tok-o">{</span>
<span class="tok-k">def</span> <span class="tok-n">value</span> <span class="tok-k">=</span> <span class="tok-mi">12</span>
<span class="tok-o">}</span>
<span class="tok-c1">// bellow won't compile</span>
<span class="tok-k">val</span> <span class="tok-k">_</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">SimpleContainer</span> <span class="tok-k">with</span> <span class="tok-nc">OnlyNumbers</span> <span class="tok-o">{</span>
<span class="tok-k">def</span> <span class="tok-n">value</span> <span class="tok-k">=</span> <span class="tok-s">""</span> <span class="tok-c1">// error: type mismatch; found: String(""); required: this.A</span>
<span class="tok-o">}</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>So, as you can see we can use Abstract Type members, in similar situations like we use Type Parameters, but without the pain of having to pass them around explicitly all the time - the passing around happens because it is a field. The price paid here though is that we bind those types by-name.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="self-recursive-type"><a class="anchor" href="#self-recursive-type"></a>12. Self-Recursive Type</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Self-recursive Types are referred to as <strong>F-Bounded Types</strong> in most literature, so you may find many articles or blog posts refering to "F-bounded". Actually, this is just another name for "self-recursive" and stands for situations where <em>the subtype constraint itself is parametrized by one of the binders occurring on the left-hand side</em>. Since the wording self-recursive is more intuitive, let’s stick to it for the rest of the section (while the subsection title being aimed for people who try to google what "F-bounded" means).</p>
</div>
<div class="sect2">
<h3 id="f-bounded-type"><a class="anchor" href="#f-bounded-type"></a>12.1. F-Bounded Type</h3>
<div class="paragraph">
<p>While this not being a Scala specific type, it still sometimes raises a few eyebrows. One example of a self-recursive type many of us are (perhaps unknowingly) familiar with, is Java’s <code>Enum<E></code>, if you’re curious about it, check out the <a href="http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Enum.java">Enum sources from Java</a>. But now back to Scala and first let’s see what we’re actually talking about.</p>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="icon-tip" title="Tip"></i>
</td>
<td class="content">
For this section we will not dive deep very deep into this type. If you’re curious for a more in-depth use-case in Scala, you may look into Kris Nuttycombe’s <a href="http://logji.blogspot.se/2012/11/f-bounded-type-polymorphism-give-up-now.html">F-Bounded Type Polymorphism Considered Tricky</a>.
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Imagine you have some <code>Fruit</code> trait, and both an <code>Apple</code> and an <code>Orange</code> extend it. The Fruit trait also has an "compareTo" method, and here the problem comes up: imagine you’d want to say "<em>I can’t compare oranges with apples, they’re totally different things!</em>". First let’s look at how we loose this compile-time safety with the naive implementation:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-c1">// naive impl, Fruit is NOT self-recursively parameterised</span>
<span class="tok-k">trait</span> <span class="tok-nc">Fruit</span> <span class="tok-o">{</span>
<span class="tok-k">final</span> <span class="tok-k">def</span> <span class="tok-n">compareTo</span><span class="tok-o">(</span><span class="tok-n">other</span><span class="tok-k">:</span> <span class="tok-kt">Fruit</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Boolean</span> <span class="tok-o">=</span> <span class="tok-kc">true</span> <span class="tok-c1">// impl doesn't matter in our example, we care about compile-time</span>
<span class="tok-o">}</span>
<span class="tok-k">class</span> <span class="tok-nc">Apple</span> <span class="tok-k">extends</span> <span class="tok-nc">Fruit</span>
<span class="tok-k">class</span> <span class="tok-nc">Orange</span> <span class="tok-k">extends</span> <span class="tok-nc">Fruit</span>
<span class="tok-k">val</span> <span class="tok-n">apple</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Apple</span><span class="tok-o">()</span>
<span class="tok-k">val</span> <span class="tok-n">orange</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Orange</span><span class="tok-o">()</span>
<span class="tok-n">apple</span> <span class="tok-n">compareTo</span> <span class="tok-n">orange</span> <span class="tok-c1">// compiles, but we want to make this NOT compile!</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>So in the naive implementation, since the trait <code>Fruit</code> has no clue about the types extending it, so it’s not possible to restrict the compareTo signature to only allow "<em>the same subclass as `this`</em>" in the parameter. Let’s now rewrite this example to use an <strong>Self Recursive Type Parameter</strong>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">trait</span> <span class="tok-nc">Fruit</span><span class="tok-o">[</span><span class="tok-kt">T</span> <span class="tok-k"><:</span> <span class="tok-kt">Fruit</span><span class="tok-o">[</span><span class="tok-kt">T</span><span class="tok-o">]]</span> <span class="tok-o">{</span>
<span class="tok-k">final</span> <span class="tok-k">def</span> <span class="tok-n">compareTo</span><span class="tok-o">(</span><span class="tok-n">other</span><span class="tok-k">:</span> <span class="tok-kt">Fruit</span><span class="tok-o">[</span><span class="tok-kt">T</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Boolean</span> <span class="tok-o">=</span> <span class="tok-kc">true</span> <span class="tok-c1">// impl doesn't matter in our example</span>
<span class="tok-o">}</span>
<span class="tok-k">class</span> <span class="tok-nc">Apple</span> <span class="tok-k">extends</span> <span class="tok-nc">Fruit</span><span class="tok-o">[</span><span class="tok-kt">Apple</span><span class="tok-o">]</span>
<span class="tok-k">class</span> <span class="tok-nc">Orange</span> <span class="tok-k">extends</span> <span class="tok-nc">Fruit</span><span class="tok-o">[</span><span class="tok-kt">Orange</span><span class="tok-o">]</span>
<span class="tok-k">val</span> <span class="tok-n">apple</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Apple</span>
<span class="tok-k">val</span> <span class="tok-n">orange</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Orange</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>Notice the Type Parameter in Fruit’s signature. You could read it as "I take some <code>T</code>, that <code>T</code> must be a <code>Fruit[T]</code>", and the only way to satisfy such bounds is by extending this trait as we do with <code>Apple</code> and <code>Orange</code> now. Now if we’d try comparing <code>apple</code> to <code>orange</code> we’ll get a compile time error:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="repl language-repl">scala> orange compareTo apple
<console>:13: error: type mismatch;
found : Apple
required: Fruit[Orange]
orange compareTo apple
scala> orange compareTo orange
res1: Boolean = true</code></pre>
</div>
</div>
<div class="paragraph">
<p>So now we’re sure we’ll only ever compare apples with apples, and other Fruit with the same kind (<em>sub-class</em>) of <code>Fruit</code>. There’s more to discuss here though - what about subclasses of <code>Apple</code> and <code>Orange</code>? Well, because we "filled-in" the type parameter at Apple / Orange level in the type hierarchy, we basically said "apples can only be compared to apples", which means that sub-classes of apples, can be compared with each other - Fruit’s signature of <code>compareTo</code> will still be happy, because the right hand side of our call would be some <code>Fruit[Apple]</code> — only a bit more concrete, for example let’s try this with a japanese apple (ja. "りんご", "ringo") and a polish apple (pl. "Jabłuszko"):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-k">object</span> <span class="tok-nc">`りんご`</span> <span class="tok-k">extends</span> <span class="tok-nc">Apple</span>
<span class="tok-k">object</span> <span class="tok-nc">Jabłuszko</span> <span class="tok-k">extends</span> <span class="tok-nc">Apple</span>
<span class="tok-n">`りんご`</span> <span class="tok-n">compareTo</span> <span class="tok-nc">Jabłuszko</span>
<span class="tok-c1">// true</span>
</code></pre>
</div>
</div>
<div class="admonitionblock tip">
<table>
<tr>
<td class="icon">
<i class="icon-tip" title="Tip"></i>
</td>
<td class="content">
You could get the same type-safety using more fancy tricks, like path dependent types or implicit parameters and type classes. But the simplest thing that does-the-job here would be this.
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="type-constructor-span-style-color-red-span"><a class="anchor" href="#type-constructor-span-style-color-red-span"></a>13. Type Constructor <span style="color:red">✗</span></h2>
<div class="sectionbody">
<div class="paragraph">
<p>Type Constructors act pretty much like functions, but on the type level.
That is, if in normal programming you can have a function that takes a value <code>a</code> and returns a value <code>b</code> based on the previous one, then in type-level programming you’d think of a <code>List[+A]</code> being a type constructor, that is:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>List[+A]</code> takes a type parameter (<code>A</code>),</p>
</li>
<li>
<p>by itself it’s not a valid type, you need to fill in the <code>A</code> somehow - "<em>construct the type</em>",</p>
</li>
<li>
<p>by filling it in with <code>Int</code> you’d get <code>List[Int]</code> which is a concrete type.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Using this example, you can see how similar it is to normal constructors - with the only difference that here we work on types, and not instances of objects. It’s worth reminding here that in Scala it is not valid to say something is of type <code>List</code>, <strong>unlike in Java</strong> where javac would put the <code>List<Object></code> for you. Scala is more strict here, and won’t allow us to use <code>just a List</code> in the place of a type, as it’s expecting a real type - not a type constructor.</p>
</div>
<div class="paragraph">
<p>Related to this subject is that with <strong>Scala 2.11.x</strong> we’re getting a new power user command in the REPL - the <code>:kind</code> command. It allows you to check if a type is higher kind or not. Let’s check it our on a simple type constructor, such as <code>List[+A]</code> first:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code class="scala language-scala"><span class="tok-c1">// Welcome to Scala version 2.11.0-M5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0-ea).</span>
<span class="tok-c1">// Type in expressions to have them evaluated.</span>
<span class="tok-k">:</span><span class="tok-kt">kind</span> <span class="tok-kt">List</span>
<span class="tok-c1">// scala.collection.immutable.List's kind is F[+A]</span>
<span class="tok-k">:</span><span class="tok-kt">kind</span> <span class="tok-kt">-v</span> <span class="tok-kt">List</span>
<span class="tok-c1">// scala.collection.immutable.List's kind is F[+A]</span>
<span class="tok-c1">// * -(+)-> *</span>
<span class="tok-c1">// This is a type constructor: a 1st-order-kinded type.</span>
</code></pre>
</div>
</div>
<div class="paragraph">
<p>Here we see that scalac is able to tell us that <code>List</code>, in fact, is a type constructor (it’s way more talkative when used with the <code>-verbose option). Let's investigate the syntax right above this information: `* -> *</code>. This syntax is widely used to represent kinds, and actually I found it quite Haskell inspired - as this is the syntax Haskell uses to print types of functions. The most intuitive way to read it out loud would be "takes one type, returns another type". You might have noticed that we’ve omitted something from Scala’s exact output, the plus sign from the relation (as in:<code>* -(+)-> *</code>), this means variance bounds and you can read up in detail about variance in section <a href="#type-variance-in-scala">Type Variance in Scala</a>.</p>
</div>
<div class="paragraph">
<p>As already mentioned, <code>List[+A]</code> (or <code>Option[+A]</code>, or <code>Set[+A]</code>… or anything that has one type parameter) is the simplest case of a type constructor - these take <strong>one</strong> parameter.
We refer to them as <strong>first-order kinds</strong> (<code>* -> *</code>). It’s also worth mentioning that even a <code>Pair[+A, +B]</code> (which we can represent as <code>* -> * -> *</code>) is still not a "higher-order kind" - it’s still <strong>first-order</strong>. In the next section we’ll dissect what exactly higher kinds give us and how to notice one.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="higher-order-kind-span-style-color-red-span"><a class="anchor" href="#higher-order-kind-span-style-color-red-span"></a>14. Higher-Order Kind <span style="color:red">✗</span></h2>
<div class="sectionbody">
<div class="admonitionblock warning">
<table>
<tr>
<td class="icon">
<i class="icon-warning" title="Warning"></i>
</td>
<td class="content">
TODO nothing here yet, coming soon…