Write a code and find the get operation fails to obtain the value from a map with enum key.
For example, the checkers
is initilized, then the get
operations always return null. Why
class Test {
static void main(String[] args){
Map<CHANA_OPERATION, Closure> checkers = [VIDEO_GENERATION: (userId) -> {
System.out.println("..............")
}, TEXT_API_CALL: (userId)->{
return false
}]
checkers.get(CHANA_OPERATION.VIDEO_GENERATION).call(1)
}
enum CHANA_OPERATION{
VIDEO_GENERATION(0),
TEXT_API_CALL(1),
TEXT_VIDEO_API_CALL(2)
int code
CHANA_OPERATION(int code){
this.code = code
}
}
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke method call() on null object
at org.codehaus.groovy.runtime.NullObject.invokeMethod(NullObject.java:110)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:44)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.NullCallSite.call(NullCallSite.java:34)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:139)
at com.chana.application.service.impl.Test.main(Test.groovy:11)
You are not actually using the enum here. The map literal in Groovy uses String keys and the quotes are optional (if the key can be parsed as one token).
To use proper values for the keys, you have to put the value inside parenthesis. You also have to reference the enum-class.
E.g.
Map<CHANA_OPERATION, Closure> checkers = [
(CHANA_OPERATION.VIDEO_GENERATION): { userId ->
// X~~~~~~~~~~~~~~~~ X
println "userId=$userId"
}, //...
]