2

I've got such piece of code:

private String getUsername(PersonalAccount account) {
    User usr = (User)account?.usr
    String name = usr?.getName()
    return name
}

And in PersonalAccount class we've got field:

SimpleUser usr

User extends SimpleUser

What means this: ?. in this two lines?

User usr = (User)account?.usr
    String name = usr?.getName()
tim_yates
  • 167,322
  • 27
  • 342
  • 338
mattis
  • 211
  • 3
  • 10

1 Answers1

5

That's not Java, that's Groovy. If it was Java you'd have semicolons ending each statement.

The method returns the name of the user on the account passed in, or null if the account is null or if the user is null.

It uses the safe-navigation operator. The safe-navigation operator evaluates to null if the operand is null, otherwise evaluates to the result of the method call. That way, if you have a method call on something that might be null, you don't have to worry about getting a NullPointerException.

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
  • 6
    @paulsm4: Wrong. It was decided to not be included in the language; as of Java 7 the `?.` operator is not part of the language. Edit to add: In fact, your *very* link says that at the top of the document: "*This feature has been removed from the final feature list that is being included in Java 7.*" – jason Aug 12 '13 at 20:33
  • @Nathan Hughes: You solved my riddle. Thanks! – mattis Aug 12 '13 at 20:42