Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify character literal in groovy?

Tags:

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.

like image 836
Kshitiz Sharma Avatar asked Jan 07 '14 11:01

Kshitiz Sharma


People also ask

How do I assign a String in Groovy?

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.

What does == mean in Groovy?

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.

How do you define a variable in Groovy?

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.


2 Answers

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.

like image 172
Kshitiz Sharma Avatar answered Sep 27 '22 00:09

Kshitiz Sharma


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

like image 26
tim_yates Avatar answered Sep 27 '22 00:09

tim_yates