Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we need @lazy property in Groovy, what's its advantages?

One of the most confusing concepts when I've learnt Groovy is : lazy property. Can't find similarly anything from C/C++ Does anyone know why we need this stuff and how we can live without it, or alternative way to do. Appreciate any help :)

like image 951
Shuyamaru Avatar asked Jun 11 '14 04:06

Shuyamaru


People also ask

What is a property in Groovy?

When a Groovy class definition declares a field without an access modifier, then a public setter/getter method pair and a private instance variable field is generated which is also known as "property" according to the JavaBeans specification.

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

What are interfaces in Groovy?

Interfaces. An interface defines a contract that a class needs to conform to. An interface only defines a list of methods that need to be implemented, but does not define the methods implementation. An interface needs to be declared using the interface keyword.

What is new keyword in Groovy?

The @Newify transformation annotation allows other ways to create a new instance of a class. We can use a new() method on the class or even omit the whole new keyword. The syntax is copied from other languages like Ruby and Python.


1 Answers

@Lazy annotation in groovy is normally used for a field within an object which is time or memory expensive to create. With this annotation the field value in the object is not calculated when you create an instance of the object, instead of is calculated when you make the first call to get it.

So i.e you create an instance of an object but you don't get the field with @Lazy annotation the field value is never calculated so you're saving time execution and memory resources. Look on the code sample (the sample has nonsense but I hope that can help to understand the explanation):

// without lazy annotation with this code token.length is calculated even
// is not used
class sample{
    String token
    Integer tokenSize = { token?.length() }()
}

def obj = new sample()
obj.token = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa'

// with Lazy annotation tokenSize is not calculated because the code
// is not getting the field.
class sample{
    String token
    @Lazy tokenSize = { token?.length() }()
}

def obj = new sample()
obj.token = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaa'

Hope this helps,

like image 125
albciff Avatar answered Sep 22 '22 07:09

albciff