Why does actually Kotlin lacks extension functions...
# announcements
e
Why does actually Kotlin lacks extension functions (like
apply
or
let
) which return
Unit
? Something like
fun <T> T.end(block: T.() -> Unit): Unit
v
When would you like to use those over the
let
or
apply
?
e
fun returnsUnit() = doSomething.end { ... }
Instead of
Copy code
fun returnsUnit() {
  doSomething.apply { ... }
}
g
I think it will make situation with scoped functions even worse (there are a lot of blog posts with explanation of let/apply/run)
I also think that use expression body syntax for unit return is bad style, because make code less obvious
s
I've been sorta wondering about this as well. For those cases where I don't care about the return value, then I don't know whether to use
apply
or
run
as I could essentially use either. 😛
e
@gildor Un contraire, it makes it more expressive -
end
in the end of an evaluation chain signalizes right away that the function doesn't return anything, moreover, such chains are more straightforward and are subjects to be lazified, if it's needed. But the best reason for such a question of me is still the same - there are a lot of cases when a function contains a single operator, which could be turned into single-line expression if only there was something like
end
. Quick example - Glide's chains
@sindrenm there are sometimes circumstances when a function has to return
Unit
, unfortunately
?:^)
g
Yes, but block body without return type looks much more expressive for me and easy to read
Expression body useful to skip return type declaration, but unit functions already do this, you can omit unit return type
👍 1
I still don't see improvement comparing to block body syntax with implicit unit return type for cases like chain calls
e
Expression bodies is also a great instrument to get rid of syntax mistakes, coming from curly braces, and lack of curly braces almost always imrpoves readability after all. Take any language where there are no curly braces at all, for example, Python (I really don't like it, but it is way one of the best examples of a good syntax). And again, functions like
Copy code
fun reloadImage() {
  Glide.load(cachedUrl)
    .asDrawable()
    .apply(...)
    .apply {
      ...
    }
}
Does not seem to be really expressive and laconic, as Kotlin was intended to be
u
well you can always append a
asUnit()
or something like that to throw away the returned value in case you really want to use an expression
g
The main reason why I think block body for unit functions is better is it always clear for me that this is side effect function and returns unit if I see block body and no return type, all other ways to do that, such as proposed
end
or
asUnit
still require more focus to understand
u
Fair enough. Personally, I have that weird urge to try to use expressions whenever I can. Must be something psychological 😉