My project has code like the following:
params.stringValue?.trim().replaceAll('aa', 'a')
We expected that if params.stringValue
was null, that both trim()
and replaceAll()
would not be called.
However we were getting a NullPointerException
on this line saying that replaceAll()
cannot be called on a null Object.
We had to change the code to be like this:
params.stringValue?.trim()?.replaceAll('aa', 'a')
Why does the first code snippet above not work? Is this a bug in Groovy that it continues to evaluate the expression after a null has been encountered once?
I don't think your assumption was correct. this:
params.stringValue?.trim().replaceAll('aa', 'a')
does not mean:
if(params.stringValue is null)
dont proceed to trim() and replaceAll()
It rather means:
if(params.stringValue is null)
skip trim() without complain but pass null to replaceAll()
so you need to say:
params.stringValue?.trim()?.replaceAll('aa', 'a')
This will skip both trim()
and replaceAll()
if the incoming argument is null.
Your assumption is only partially correct.
The ?
-operator doesn't break the execution in case of null, it blocks calling the current method, and returns a null
instead, which is why it's necessary also to protect the right-hand side of the chain with ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With