I keep trying to do `return <whatever>` from...
# getting-started
j
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
It is only possible in inline functions
So no magic
j
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
The majority of lambda-accepting methods are inline for performance reasons
j
oh great.. and the
filter
too then (I missed that one)
s
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
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
hmmm there looks like two calls to
.count()
though
j
Yeah but the second is just
count()
- no predicate, so it just returns
size
s
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
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
perhaps ¯\_(ツ)_/¯