-
Notifications
You must be signed in to change notification settings - Fork 3
/
Union.java
105 lines (93 loc) · 2.46 KB
/
Union.java
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
/*
* File: Union.java
* Description: Seeks to emulate the super-awesome union data-types in C using
* Java's generics. Sadly (luckily?) it is type-safe.
* Author: Benjamin David Mayes <[email protected]>
*/
/**
* A Union superclass that encompasses Left and Right Union types.
*/
public class Union<A,B> {
/**
* Constructs a new Union with no data. This should not be called by any
* class except for subclasses.
*/
private Union() {
}
/**
* Obtains data that is of type A.
*
* @return The data of type A or null if there if it is storing data of type B.
*/
public A left() {
return null;
}
/**
* Obtains data that is of type A.
*
* @return The data of type A or null if there if it is storing data of type B.
*/
public B right() {
return null;
}
/**
* A Union holding data of type A.
*/
public static class Left<A,B> extends Union<A,B> {
A myA;
/**
* Constructs a union that uses type A.
*
* @param a The data held by the union.
*/
public Left( A a ) {
myA = a;
}
/**
* Overrides left() so that it returns the actual data held by the union.
*
* @return The data held by the union.
*/
public A left() {
return myA;
}
/**
* Obtains a String representation of the object held by the Union.
*
* @return A String representation of the object held by the Union.
*/
public String toString() {
return myA.toString();
}
}
/**
* A union holding data of type B.
*/
public static class Right<A,B> extends Union<A,B> {
B myB;
/**
* Constructs a union that uses type A.
*
* @param a The data held by the union.
*/
public Right( B b ) {
myB = b;
}
/**
* Overrides right() so that it returns the actual data held by the union.
*
* @return The data held by the union.
*/
public B right() {
return myB;
}
/**
* Returns a string representation of the object held by the Union.
*
* @return A string representation of the object held by the Union.
*/
public String toString() {
return myB.toString();
}
}
}