How to specify character literal in groovy?
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
There a three ways to use char literals in Groovy:
char c = 'c' /* 1 */
'c' as char /* 2 */
(char) 'c' /* 3 */
println Character.getNumericValue(c) /* 1 */
println Character.getNumericValue('c' as char) /* 2 */
println Character.getNumericValue((char) 'c') /* 3 */
If you assign a String literal like 'c' to a variable, Groovy does the cast implicitly (see /* 1 * /). If you want use the String literals without variables, you have to cast them by using ...as char... (see /* 2 * /) or ...(char)... (see /* 3 * /).
The usage of char literals in methods without casting them is not possible as Groovy has only String literals which must be casted to char.
println Character.getNumericValue('c') // compile error