Paul Woitaschek
10/22/2017, 12:37 PMTN
without writing that code manuallykarelpeeters
10/22/2017, 12:39 PMdr.henry
10/22/2017, 1:27 PMkarelpeeters
10/22/2017, 1:28 PM&&
.dr.henry
10/22/2017, 1:50 PMkarelpeeters
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
.dr.henry
10/22/2017, 2:06 PMkarelpeeters
10/22/2017, 2:12 PMdr.henry
10/22/2017, 2:23 PMkarelpeeters
10/22/2017, 2:23 PMkarelpeeters
10/22/2017, 2:24 PMlazy(computeFoo)
.karelpeeters
10/22/2017, 2:25 PM10
) and you're specifying the type explicitly.karelpeeters
10/22/2017, 2:26 PMlazy(computeFoo)
is the same as lazy{computeFoo()}
btw, Idea wil even suggest changing it.dr.henry
10/22/2017, 2:27 PMkarelpeeters
10/22/2017, 2:28 PMkarelpeeters
10/22/2017, 2:28 PMdr.henry
10/22/2017, 2:32 PMkarelpeeters
10/22/2017, 2:34 PMkarelpeeters
10/22/2017, 2:34 PMdr.henry
10/22/2017, 2:44 PMpoohbar
10/22/2017, 3:24 PMDouble?
but I want to expose it as Double
because I know it can't be nullkarelpeeters
10/22/2017, 3:25 PMval _num: Double? = 3d
val num get() = _num!!
poohbar
10/22/2017, 3:26 PMMike Lynch
10/22/2017, 3:50 PMkarelpeeters
10/22/2017, 3:53 PMx: Short
somewhere?Mike Lynch
10/22/2017, 3:54 PMMike Lynch
10/22/2017, 3:57 PMMike Lynch
10/22/2017, 3:58 PMkarelpeeters
10/22/2017, 4:00 PMwhen(x.toInt()) { ... }
?