4

I'm using Groovy 1.8.3 (in Grails 2.0). I need to declare some float arrays, and am using the standard java syntax, e.g.:

 float rentVal[] = {1.37f, 1.69f, 2.07f, 2.53f}

The compiler errors on this, saying: expecting '}', found '='

Perhaps because it's late night (pacific time) I'm confusing something here. My question is what's the right way to do this in Groovy.

Thanks

1 Answer 1

8

Tried this in GroovyConsole:

groovy> def rentVal = [1.37f, 1.69f, 2.07f, 2.53f] as float[] 
groovy> rentVal.class 

Result: class [F 

EDIT, it's enough to do this:

float[] a = [1.0f, 2.3f, 3.4f]
Sign up to request clarification or add additional context in comments.

5 Comments

Yes, I've tried this in GroovyConsole. What result did you get?
Thanks much, I made a typo, what you gave did work. An additional question: is it a bug that Groovy doesn't allow for the standard Java syntax here?
Also, you have to remember arrays in Groovy are really Lists. To cast them to primitive arrays, you have to use the as operator.
Thanks much Socha for the reference and also the explanation. I had thought Groovy was a pure superset of Java (syntax), but apparently this is not the case -- i.e. you can't use Java syntax in all cases.
@socha23 Arrays aren't Lists, String[] a = [ 'a', 'b', 'c' ] is perfectly valid groovy and will give you an array of String. It's just Groovy will give you lists unless you specifically ask for an Array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.