File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change @@ -55,6 +55,44 @@ val res3: t2.Option.Some[Int] = Some(2)
55
55
scala> scala> new Option .Some (2 )
56
56
```
57
57
58
+ As all other enums, ADTs can have methods on both the enum class and
59
+ its companion object. For instance, here is ` Option ` again, with an
60
+ ` isDefined ` method and an ` Option(...) ` constructor.
61
+
62
+ ``` scala
63
+ enum class Option [+ T ] {
64
+ def isDefined : Boolean
65
+ }
66
+ object Option {
67
+ def apply [T >: Null ](x : T ): Option [T ] =
68
+ if (x == null ) None else Some (x)
69
+
70
+ case Some [+ T ](x : T ) {
71
+ def isDefined = true
72
+ }
73
+ case None {
74
+ def isDefined = false
75
+ }
76
+ }
77
+ ```
78
+
79
+ Enumerations and ADTs have been presented as two different
80
+ concepts. But since they share the same syntactic construct, they can
81
+ be seen simply as two ends of a spectrum and it is perfectly possible
82
+ to conctruct hybrids. For instance, the code below gives an
83
+ implementation of ` Color ` either with three enum values or with a
84
+ parameterized case that takes an RGB value.
85
+
86
+ ``` scala
87
+ enum Color (val rgb : Int ) {
88
+ case Red extends Color (0xFF0000 )
89
+ case Green extends Color (0x00FF00 )
90
+ case Blue extends Color (0x0000FF )
91
+ case Mix (mix : Int ) extends Color (mix)
92
+ }
93
+ ```
94
+
95
+
58
96
59
97
60
98
Original file line number Diff line number Diff line change @@ -24,3 +24,21 @@ enum Color(val rgb: Int) {
24
24
case Mix (mix : Int ) extends Color (mix)
25
25
}
26
26
27
+ object t3 {
28
+
29
+ enum class Option [+ T ] {
30
+ def isDefined : Boolean
31
+ }
32
+ object Option {
33
+ def apply [T >: Null ](x : T ): Option [T ] =
34
+ if (x == null ) None else Some (x)
35
+
36
+ case Some [+ T ](x : T ) {
37
+ def isDefined = true
38
+ }
39
+ case None {
40
+ def isDefined = false
41
+ }
42
+ }
43
+
44
+ }
You can’t perform that action at this time.
0 commit comments