简体   繁体   中英

How to specify character literal in groovy?

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.

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

This response is rather late! But just stumbled upon it and wanted to add some clarification.

The more accurate Answer is unlike Java, Groovy does NOT have a character literal, but you can cast a string to a character. A literal is a value that is written exactly as it is to be interpreted, and the necessity of the type cast indicates it is NOT truly a literal.

Examples:

assert 'a'.class != Character.class
assert 'a'.class == String.class
assert ('a' as char).class == Character.class
assert ((char)'a').class == Character.class
char A = 'a'; // implicit coercion of string to char
assert A.class == Character.class

In contrast, both groovy and Java support numeric literals for int, long, double, and float, but do not support numeric literal for short.

Examples:

assert 42.class == Integer.class
assert 42l.class == Long.class
assert 42f.class == Float.class
assert 42d.class == Double.class
assert (42 as Short).class == Short.class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM