Skip to content

Instantly share code, notes, and snippets.

@jimklimov
Created February 13, 2023 19:04
Show Gist options
  • Save jimklimov/366aab999d7699a0a72794e42c8c03dd to your computer and use it in GitHub Desktop.
Save jimklimov/366aab999d7699a0a72794e42c8c03dd to your computer and use it in GitHub Desktop.
groovy enum fun
enum mpciEnumPatchapplStrategies {
MERGE("merge", "mrg"),
ADDDIFF("addDiff"),
BOGUS();
final static def addDiff = ADDDIFF, merge = MERGE, adddiff = ADDDIFF;
static {
def oldAsType = String.metaClass.getMetaMethod("asType", [Class] as Class[])
String.metaClass.asType = { Class type ->
type.isAssignableFrom(mpciEnumPatchapplStrategies) ?
mpciEnumPatchapplStrategies.fromString(delegate) :
oldAsType.invoke(delegate, [type] as Class[])
}
}
final Set<String> aliases;
//final String value;
mpciEnumPatchapplStrategies(String... v) {
this.aliases = v;
}
//mpciEnumPatchapplStrategies(String v) {
// this.value = v;
//}
static {
mpciEnumPatchapplStrategies.metaClass.mpciEnumPatchapplStrategies = { def s ->
if (s instanceof mpciEnumPatchapplStrategies)
return s
if (s instanceof String)
return mpciEnumPatchapplStrategies.fromString(s)
return null
}
}
static valuesString() {
values().collect {it.toString() + " (${it.name()})"}
}
static fromString(String v) {
return values().find {(v in it.aliases || it.name().equals(v))} ?: null
}
String toString() {
this.aliases[0] ?: this.name()
}
}
println GroovySystem.version
for (v in mpciEnumPatchapplStrategies.valuesString()) {
println "${v.class}: '${v}'"
}
println "=== s1"
def s1 = mpciEnumPatchapplStrategies.adddiff
println s1
println "=== s2"
def s2 = mpciEnumPatchapplStrategies.ADDDIFF
println s2
println "=== s3"
mpciEnumPatchapplStrategies s3 = mpciEnumPatchapplStrategies.ADDDIFF
println s3
println "=== s4"
mpciEnumPatchapplStrategies s4 = 'ADDDIFF'
println s4
println "=== s5"
mpciEnumPatchapplStrategies s5 = 'addDiff' as mpciEnumPatchapplStrategies
println s5
println "=== s6"
mpciEnumPatchapplStrategies s6 = 'ADDDIFF' as mpciEnumPatchapplStrategies
println s6
println "=== s7"
def s7 = 'ADDDIFF' as mpciEnumPatchapplStrategies
println s7
println "=== s8"
def s8 = 'addDiff' as mpciEnumPatchapplStrategies
println s8
println "=== s9 (adddiff => null - no such alias)"
def s9 = 'adddiff' as mpciEnumPatchapplStrategies
println s9
println "=== s10 (mrg => merge)"
def s10 = 'mrg' as mpciEnumPatchapplStrategies
println s10
println "=== s11 (addDiff)"
def s11 = mpciEnumPatchapplStrategies.fromString('addDiff')
println s11
println "=== s11 again (bogus DEF should not fail?)"
s11 = 'chew'
println s11
// should crash
println "=== s6 again (bogus ENUM type should fail)"
s6 = 'chew'
println s6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment