Groovy lazy object construction

283 views Asked by At

I have a class that can be created by passing a list of strings or by passing a file. The file will be parsed, creating a list of strings. So it's actually a helper constructor.

Parsing the file may take a long time however and the resulting list of strings may not be used ever (even though the object is created anyways). Therefore I got the idea of "lazy parsing" the file so that the file is actually only parsed right before some methods of this objects are used.

Is there any way to do this in groovy or even a better way to achieve what I want?

2

There are 2 answers

2
albertovilches On

Don't parse the content in the constructor, just store the String or the File constructor parameters in attributes in your class. Then create a new method with the slow parse using the previous attributes. Finally, you can cache the result annotating this method with the @Memoized Groovy annotation.

0
valenterry On

I have used a workaround now. I save both the file or the string list given in one of the constructors in the fields (the other one is null). Then I create a third lazy field which accesses the non-null-property (whatever it is) and if it's the file it parses it.

That's rather complicated but I think it's the only way to use lazyness with arguments passed into the constructor that shall be lazily evaluated.