0

I am learning groovy, I am using the documentation and some youtube videos. I want for testing to find out how to declare an array of objects, but that array will have a x number of objects depending on some stuff. Here is what I tried:

class Issue {
    String type = ""
    String severity = ""
    String linestart = "" 
    String filename = "" 
    String meesage = "" 
}

def test(){
    Issue[] Issues = new Issue[5] 
    Issues[0].type = "error"
    println Issues[0].type
}

test()

what I get:

Caught: java.lang.NullPointerException: Cannot set property 'type' on null object
java.lang.NullPointerException: Cannot set property 'type' on null object

I assume my array does not have 5 Issues objects inside, and that is why is trying to set on null object. How would be the right syntax to do so?

0

1 Answer 1

1

You are right- all the values are initially null. You have to first create instances of Issue and assign it to the array elements,

Issues[0] = new Issue()
Issues[0].type = "error"

alternatively, using "groovy" syntax,

Issues[0] = new Issue(type: "error")
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for answering. I am wondering now if it is better to use a class or a map for this case...and how to create a list of maps
peronally, i would use a list of objects here, List<Issue> issues You have a well defined class which is preferable to using a map of properties

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.