https://kotlinlang.org logo
Title
j

Jay

01/29/2019, 1:53 PM
I keep trying to do
return <whatever>
from lambdas - I know I just need to remove the
return
, but can anyone explain the error message to me? From the expected type it looks as if the
return
from within the lambda is capable of terminating the enclosing function call - how is this possible? Would this pop the stack from the lambda, the
partition
call, and the enclosing function - like a
throw
?
s

spand

01/29/2019, 1:56 PM
It is only possible in inline functions
So no magic
j

Jay

01/29/2019, 2:28 PM
Ahh I see - so the lambda, and the partition function get inlined directly into the enclosing function. Got it - so is there a way to know when this will happen? Or will it just be that in some cases I could short-cut return straight from the middle of an operation, and sometimes not?
s

Shawn

01/29/2019, 2:29 PM
The majority of lambda-accepting methods are inline for performance reasons
j

Jay

01/29/2019, 2:30 PM
oh great.. and the
filter
too then (I missed that one)
s

Shawn

01/29/2019, 2:31 PM
yeah, most of the functional collections extensions are inlined
at some point you may find a lambda may be
crossinline
, which disallows non-local returns, but isn’t quite the silver bullet you’re looking for
in my experience it’s also kind of rare to actually see libraries use it, but that just may be my inexperience showing
j

Jay

01/29/2019, 2:37 PM
This is from the Kotlin Koans, and it asks you to implement it using
partition
. However I initially didn’t see this and implemented it using what I’d learned so far. However looking at the code again, will the
partition
in my example create two collections vs the commented out implementation which doesn’t create any collections and just iterates the existing one once (in the
count{}
)?
s

Shawn

01/29/2019, 2:39 PM
hmmm there looks like two calls to
.count()
though
j

Jay

01/29/2019, 2:40 PM
Yeah but the second is just
count()
- no predicate, so it just returns
size
s

Shawn

01/29/2019, 2:42 PM
in any case, the extra collections are more or less just views on the original collection, I’m pretty sure
the extra class allocation is worth the reduced complexity, I feel like
I haven’t quite had my morning coffee, however, so I could definitely be wrong lol
j

Jay

01/29/2019, 2:43 PM
CMD-clicking
partition
takes me to the implementation which creates two array lists.
I think it’s probably a bad example of where to use
partition
.
s

Shawn

01/29/2019, 2:44 PM
perhaps ¯\_(ツ)_/¯