red888
red888

Reputation: 31550

groovy null safe operator not working

Trying to do this:

var = obj?.Prop ?: obj.Prop.toLowerCase()

But I keep getting:

java.lang.NullPointerException: Cannot get property 'Prop' on null object

Isn't this what ? is for? My understanding is obj?.Prop is the same as:

if ( obj != null && obj.Prop ) { .. }

Sometimes obj is null, but if its not I want to set obj.Prop to lower case- cant set toLowerCase() on a null object

Upvotes: 1

Views: 770

Answers (2)

bdkosher
bdkosher

Reputation: 5883

You'll need to do obj?.Prop?.toLowerCase()

The Elvis operator (?:) is causing obj.Prop.toLowerCase() to be evaluated when the obj?.Prop is null. It's equivalent to writing

var = (obj?.Prop != null) ? obj.Prop : obj.Prop.toLowerCase()

Upvotes: 3

Nathan Hughes
Nathan Hughes

Reputation: 96385

The expression following the ?: Is the alternative for the case where the preceding expression is null. If you use the same object in your alternative as you used in the preceding part then you will trigger an npe

Instead do

obj?.Prop?.toLowerCase()

Upvotes: 1

Related Questions