Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining Null-Safe Operator

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?

like image 689
Ask613 Avatar asked Jun 12 '15 12:06

Ask613


2 Answers

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.

like image 64
dsharew Avatar answered Nov 11 '22 16:11

dsharew


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 ?

like image 21
injecteer Avatar answered Nov 11 '22 14:11

injecteer