melatonina
03/24/2021, 2:38 PM?.let { }
expressions, in case it has not been discussed before.
Whenever, inside of an expression, a ?
(question mark) is appended to the name of a variable (mutable var
or non mutable val
) of nullable type, the whole expression containing it would evaluate to null
if that variable is null
, otherwise the variable is cast to the respective non-nullable type.
fun f(a: A): B = TODO()
fun g(a: A?): B? = f(a?)
fun h(a: Int?, b: Int): Int? = (a? + b)*2
fun i(a: Int?, b: Int?, c: Int?): Int? = (a? + b?)*c?
I don't know how to call this feature. Maybe "short-circuiting null operator"? As suggested by @uli, this feature is symmetric to the ?.
operator, and would work on all arguments of a function like ?.
does on the this
argument.
Would this syntax cause conflict with other language features? Would you consider its implementations?melatonina
03/24/2021, 2:39 PMuli
03/24/2021, 2:48 PMuli
03/24/2021, 2:49 PMuli
03/24/2021, 2:50 PMImran/Malic
03/24/2021, 2:51 PMmelatonina
03/24/2021, 8:23 PM?.
) do perform short-circuiting. The documentation says:
// If either `person` or `person.department` is null, the function is not called:
person?.department?.head = managersPool.getManager()
But you are right: these issues should be discussed and defined properly.melatonina
03/24/2021, 8:27 PMnullable
was mentioned in the original thread by @kioba. Thanks for mentioning it here too.Imran/Malic
03/24/2021, 8:41 PMmelatonina
03/24/2021, 8:53 PMvariable?
expression appears. So:
(f(a?) + 2) * g("hello")
would only short-circuit
(f(a?) + 2)
and probably cause a compile-time error. While:
(f(a?) + 2)? * g("string")
would short-circuit the whole expression.
This would be an option. I'm not sure which one I'd like more.uli
03/25/2021, 7:51 AMf(effect1()?, effect2()?)
because effect1 and effect2 are independentuli
03/25/2021, 7:54 AMmelatonina
03/25/2021, 10:03 AMuli
03/25/2021, 1:15 PM