Why do we need the @lazy property in Groovy, what are its advantages?

One of the most confusing concepts when I learned Groovy: lazy property. It is impossible to find anything from C / C ++. Does anyone know why we need this material and how we can live without it, or an alternative way to do it. Appreciate any help :)

+4
source share
1 answer

@Lazygroovy annotation is typically used for a field inside an object whose time or memory is required to create. With the help of this annotation, the value of the field in the object is not calculated when creating an instance of the object, but is not calculated on the first call to obtain it.

, , @Lazy, , . ( , , ):

// 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'

, ,

+6

Source: https://habr.com/ru/post/1544081/


All Articles