karelpeeters
10/22/2017, 1:56 PMfun example(computeFoo: () -> Foo) {
val memoizedFoo by lazy(computeFoo)
if (someCondition && memoizedFoo.isValid()){
memoizedFoo.doSomething()
}
}
Let's say computeFoo
is a slow function, and we want to avoid calling it whenever possible. In the above code, if someCondition == false
the &&
will "short-circuit", meaning it won't even bother to evaluate the right side since false && x
is guaranteed to be false
. That means that the code behind lazy
doesn't call computeFoo
at all. If on the other hand someCondition == true
, memoizedFoo.isValid()
will be evaluated, lazy
will call computeFoo
and the result will be available in memoizedFoo
.