Reputation: 16865
I want to evaluate
"user.name"
but user
might be null, which of course results in an NPE is there a way to say only try to get name if user is not null? otherwise return null.
I read about the Elvis syntax, but I'm not sure how to apply it here
Upvotes: 0
Views: 55
Reputation: 34806
You can use the safe navigation operator like this:
user?.name
This has the exact same behavior you describe - if the user is null
, the expression will be evaluated to null
, otherwise it will be evaluated to the value of user.name
.
Upvotes: 2