What’s the difference in defining a variable using "val" only and one using "Lazy"?

Asked

Viewed 74 times

1

I am studying Scala and I found some codes where several variables are defined with the syntax "Lazy". Even reading some materials in English, I could not reach a clear definition. What’s the difference between using Azy and not using?

1 answer

0

When you use Lazy variables the operation that defines the variable is only executed at the time you use the variable. Normal variables have their calculated value as soon as you define them.

val a = 10
//nesse momento a variável a já está com valor definido na memória

lazy val b = a + 1 
//nesse momento a variável b não está com valor definido na memória

val c = b + 1
//nesse momento é verificado que b ainda não foi calculado,
//então é realizado o cálculo a + 1 e o resultado salvo em b,
//por fim é definido o valor de c

The use of Lazy values is not only limited to the Scala language, several programming languages use this same concept and it can be very useful to optimize your code.

If you want to know better it’s worth taking a look:

https://pt.wikipedia.org/wiki/Lazy_loading https://blog.mxcursos.com/como-aumentar-a-velocidade-da-pagina-com-lazy-loading/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.