Wouldn’t it be nice to be able to short-circuit fu...
# language-proposals
p
Wouldn’t it be nice to be able to short-circuit functions and constructor calls when one of the params is null 👀 Has something like this been proposed? I’m not sure what to search for in YouTrack 😅 https://twitter.com/pablisc0/status/1432981029812322306?s=20
f
Isn't that exactly what extensions provide?
someNullableString?.aFunction()
p
imagine you can’t change 
aFunction
 in this example
@Fleshgrinder We could also change it to take a nullable instead 😅 But yeah making it an extension function could solve that specific case
f
You can always wrap the original function in an inline extension function. That's also how it's done in stdlib. 🙂
☝️ 1
m
I have seen this being proposed in youtrack, by the name of nullable arguments or something like that. @*Richard Fussenegger* you can't do that for multiple parameters though.
p
Yeah, thats true inline would work. And would work for constructors using a function with the same name (although requires to return the same type and not nullable). I guess it would be nice for the compiler to generate these functions for us 😅
f
No, you can't use it with multiple arguments, but then it becomes also much harder to know when the result should be null. If you have 2 parameters there are already 4 possible combinations.
f(a, b)
-
f(null, b)
-
f(a, null)
-
f(null, null)
Now mix it with a Java function where everything can be null, do we really want to short circuit out just because something is null which actually should be an error? I think that asking users to handle this explicitly is safer. That said, I definitely see how this could cut down on boilerplate. 🙂
e
p
We would only need one function:
Copy code
// given
fun f(a: A, b: B): C = ...
inline fun f(a: A?, b: B?): C? = 
  when {
    a == null -> null
    b == null -> null
    else -> f(a, b)
  }
I can see problems with ambiguity though 🙃 If the compiler was able to introduce the short-circuit it would remove the ambiguity, potentially…
Thank you @ephemient That looks close to what I was thinking about 🙂