Enhanced Enums -- use cases
Vicente Romero
vicente.romero at oracle.com
Tue Apr 11 19:32:47 UTC 2017
Hi,
Some additional examples, this one shows code sharing between enum constants
public class SharingCodeWithEnhancedEnums {
enum Primitive<X> {
INT {
// instead of replicating code INT.even() can make use of
LONG.even()
boolean even(int value) { return LONG.even(value); }
},
LONG {
boolean even(long value) { return value % 2 == 0; }
};
}
public static void main(String... args) {
// prints: true
System.out.println(Primitive.INT.even(4));
}
}
This one shows the power of sharper typing
enum EnumConstants {
BYTE {
static final int BITSIZE = 8;
},
INT {
static final int BITSIZE = 32;
};
public static void main(String... av) {
System.out.println("BYTE.BITSIZE = " + BYTE.BITSIZE); //
prints: BYTE.BITSIZE = 8
System.out.println("INT.BITSIZE = " + INT.BITSIZE); //
prints: INT.BITSIZE = 32
}
}
Thanks,
Vicente
On 04/11/2017 03:11 PM, Brian Goetz wrote:
> As you may have noticed, we pushed an implementation of Enhanced Enums
> some time ago. We're hoping to get user feedback on the feature as it
> is now implemented.
>
> To get things started, here are some typical use cases where generic
> enums might be useful. Please contribute others, as well as places in
> the JDK where code could be refactored using this feature.
>
> An obvious example is com.sun.tools.javac.code.Dynamic
> (http://hg.openjdk.java.net/valhalla/valhalla/langtools/file/85cc92a65da8/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Dynamic.java#l51),
> where we have an enum that represents the kinds of types representable
> in the constant pool.
>
> In that case, these factory methods:
>
> http://hg.openjdk.java.net/valhalla/valhalla/langtools/file/85cc92a65da8/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Dynamic.java#l137
>
>
> should be collapsible to a single generic method:
>
> <D> static BootstrapArgument<D> constant(Kind<D> kind, D data).
>
>
> Another example is command line parsing; for command line arguments,
> we can represent them as enums whose type represents the type of an
> (optional) parameter:
>
> enum Args {
> QUIET<??>("quiet", "q"),
> FILE<String>("file", "f"),
> COUNT<Integer>("count", "c"), ....
> }
>
> (though its not obvious what the type arg of QUIET should be.)
>
>
> If anyone wants to experiment and offer their experience in applying
> (or misapplying) this feature, either to the JDK or their own
> codebase, that would be appreciated....
>
>
More information about the amber-dev
mailing list