earroyoron
12/10/2020, 9:42 PMval result = run { ... }
result is not actually calculated there, but when is needed (lazy), isn't it?
I know this is the usual behaviour when using a functional style but I couldn't find any reference to give a clear explanation to my colleague.Nir
12/10/2020, 9:43 PMNir
12/10/2020, 9:43 PMNir
12/10/2020, 9:44 PM{ ... }
creates a lambda, which isn't immediately invokedNir
12/10/2020, 9:44 PMmyMap.getOrPut(key) { expensiveFunctionCall() }
Nir
12/10/2020, 9:44 PMNir
12/10/2020, 9:44 PMNir
12/10/2020, 9:45 PMearroyoron
12/10/2020, 9:52 PMresult
and I can use result
but their actual value, that is the value from the execution inside the lambda (maybe an expensiveFunction) is invoked (and then, and the end, executed) and defered only when result
is really needed... for me is "result is not actually calculated there",...earroyoron
12/10/2020, 9:54 PMval result = someMethodAsUsual(...)
then someMethodAsUsual is executed and assigned to result
just in that very moment...Casey Brooks
12/10/2020, 10:08 PM.run
is a function which immediately invokes a lambda. Thus, you create a lambda, and then by passing that lambda to .run
invoke it immediately. You can define that lambda elsewhere and assign it to a variable, and that lambda is lazily invoked, but by calling .run { }
with a lambda, the lambda itself only exists inside the .run
function, which invokes it immediately.
Consider the following snippet: https://pl.kotl.in/3oxgHL623Nir
12/10/2020, 10:13 PMval result = { foo() }
then result isn't the return value of foo, and technically it's not "the return value of foo but lazy" eitherNir
12/10/2020, 10:13 PMNir
12/10/2020, 10:14 PMNir
12/10/2020, 10:14 PMval result = bar({ foo() } )
Nir
12/10/2020, 10:14 PMNir
12/10/2020, 10:14 PMval result = bar { foo() }
Nir
12/10/2020, 10:15 PMbar
to run
:
val result = run { foo() }
then result is the return value of foo(), because that's what run
does: it executes the lambda you pass itNir
12/10/2020, 10:16 PMfun <R> dontRun(x: () -> R): Int { return 0 }
Nir
12/10/2020, 10:16 PMval result = dontRun { foo() }
Nir
12/10/2020, 10:16 PMNir
12/10/2020, 10:16 PMfoo()
is never invokedVampire
12/10/2020, 11:12 PMval result by lazy { ... }
earroyoron
12/11/2020, 6:49 AM