Skip to content

Commit 66e3819

Browse files
committed
More ADT material
1 parent 9c91536 commit 66e3819

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

docs/docs/reference/adts.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,44 @@ val res3: t2.Option.Some[Int] = Some(2)
5555
scala> scala> new Option.Some(2)
5656
```
5757

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+
5896

5997

6098

tests/pos/reference/adts.scala

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,21 @@ enum Color(val rgb: Int) {
2424
case Mix(mix: Int) extends Color(mix)
2525
}
2626

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+
}

0 commit comments

Comments
 (0)