How do I specify a character literal in groovy since both 'a' and "a" result in string?
I do not want to declare a character variable just for this purpose.
A String literal is constructed in Groovy by enclosing the string text in quotations. Groovy offers a variety of ways to denote a String literal. Strings in Groovy can be enclosed in single quotes ('), double quotes (“), or triple quotes (“””). Further, a Groovy String enclosed by triple quotes may span multiple lines.
Behaviour of == In Java == means equality of primitive types or identity for objects. In Groovy == translates to a. compareTo(b)==0, if they are Comparable, and a. equals(b) otherwise.
Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.
Using the as
keyword is the way to make a character literal in Groovy.
'a' as char
See the discussion here at Groovy's buglist.
If this is for a variable, you can also define the type, so:
import java.awt.image.* new BufferedImage( 1, 1, BufferedImage.TYPE_INT_RGB ).with { createGraphics().with { // Declare the type char aChar = 'a' // Both ways are equivalent and work assert fontMetrics.charWidth( aChar ) == fontMetrics.charWidth( 'a' as char ) dispose() } }
(apologies for the long example, but I had brain freeze, and couldn't think of a different standard java function that takes a char
) ;-)
This also goes against the second line of the question, but I thought I'd add it for completeness
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With