Smart return <https://youtrack.jetbrains.com/issue...
# language-proposals
k
Smart return https://youtrack.jetbrains.com/issue/KT-65334/Smart-flow-operatior-feature-request We have a good operator ?:
foo?: return
==
if(foo == null) return
• How about add inverse operator
foo !: return
foo !: return foo
foo !: return it
[it==foo captured value] all above equals to
if(foo!=null) return *
Case: bafore
Copy code
val errors = getErrors()
if(errors != null) return errors
we had to create val to hold result and then type if after:
getErrors() !: return it
way simplier
s
Some of this can be done with the existing
let
function
j
Yeah I think there's a better argument to be made for allowing something like
?.return
which fits into existing semantics well. Of course you can already do
?. let { return it }
which isn't too bad, like Sam said. The inverse of
?:
is already essentially
?.
.
1
k
ofc
let
is a good option, yet small improve may be good idea
?:
semantics and
?.
are too similar In tearms of readablitity -
!:
might be a bit more readable (acceptable) as
!
and
?
are feels like oppposites
!!:
is also an option
j
That doesn't seem like an option at all. Isn't the behavior to no-op if the value is null. Something with
!!
would surely throw NPE if it saw a null value.
☝️ 2
The opposite of
?
is really nothing. You can see this in types
String
vs.
String?
and function calls
foo.bar()
vs
foo?.bar()
.
I don't think we should lean-in to
?:
which is weird syntax that breaks chaining. There's a decently upvoted issue which requests a functional version of it: https://youtrack.jetbrains.com/issue/KT-15962
The "do something if non-null, else propagate null" operator exists as
?.
, so really thing the most logical thing to do (if we even agree there's a need to do anything) would be to advocate for
?.return
which should produce
Nothing?
as its expression type
k
There should be smth more usefull (sugar) reather then
someVar?.let { return(it) }
For single line checks might be for example
somveFun()?.return
someFun()?.return(smth)
or similar
Just talking about simple cases where having
?.let {return it}
migt be a bit more shorter