Karlo Lozovina
02/23/2022, 10:42 PMval previous = someField!!
someField = null
return previous
Joffrey
02/23/2022, 10:48 PM?: error("some meaningful message")
instead of !!
.
If you really want an alternative, you could do:
return someField!!.also { someField = null }
But I'm not sure it's "more elegant"Richard Gomez
02/23/2022, 10:49 PM!!
or ?: error(...)
.Karlo Lozovina
02/23/2022, 10:50 PMreturn someField!!.also { someField = null }
will return the old value, not the null that's been set inside the { } block?Joffrey
02/23/2022, 10:52 PMcheckNotNull
.
Now whether to use checkNotNull
or ?: error()
depends on how you want the program to read. I find both acceptable under certain circumstances.also
returns the value of its receiver. So first, someField!!
is evaluated and passed to also
as receiver, then also
does its thing, and then it returns whatever value was initially given to itRichard Gomez
02/23/2022, 10:57 PM!!
in general because requireNotNull
, checkNotNull
, or ?: error()
result in clearer intent and error messages.
I tend to see !!
used in two scenarios:
• "this can't be null, trust me, but the compiler isn't smart enough to determine this (e.g. .filter { it != null }
)
• "I have no idea what I'm doing and want these warnings to go away" 😄.also { }
compiles to something like:
public String foo() {
String var10000 = someField;
Intrinsics.checkNotNull(var10000);
String var0 = var10000;
int var2 = false; // I have no idea why this is here
someField = (String)null;
return var0;
}
Joffrey
02/23/2022, 11:00 PMKarlo Lozovina
02/23/2022, 11:00 PM...also { }
block was confusing at first, it's getting late here 🙂
I'm gonna go with !!
, it's basically something that should never happen, so I'm going for brevity sake