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 :)
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.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
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.
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.
@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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With