Search code examples
groovyxor

XOR on char does not work on groovy


Why this does not work with groovy?

  ('a' as char) ^ ('b' as char)​

It raises

  groovy.lang.MissingMethodException: No signature of method: java.lang.Character.xor() is applicable for argument types: (java.lang.Character) values: [b]
  Possible solutions: div(java.lang.Character), any(), any(groovy.lang.Closure), plus(java.lang.Character), is(java.lang.Object), use([Ljava.lang.Object;)
at Script1.run(Script1.groovy:2)

As far as i know it breaks compatible source with java.


Solution

  • Works with Groovy 1.8.4:

    println( ('a' as char) ^ ('b' as char) )
    

    prints

    3
    

    Groovy has quite a few places where the source is incompatible from Java. A list can be found here, there are also things like no do...while loop, etc...

    Edit

    Jochen Theodorou, the Groovy Project Tech Lead replied to the mail on the list:

    the currently "right" way is

    println( ('a' as int) ^ ('b' as int) )

    and it should still print 3. As of why it works sometimes and sometimes not... I think that is because I accidentally implemented that for the primitive optimizations. That means you get this in later 1.8 versions, because before it was not implemented. And it means it works only if they are enabled, which is the case in only specific situations.

    Edit #2

    This is looking like an issue that only shows itself with certain implementations of the JVM. As such, I have posted an issue to the Groovy Jira, so hopefully future versions of Groovy will smooth out the differences a bit :-)