smeeb
smeeb

Reputation: 29497

Groovy null and isEmpty checks on child collections

I have the following user class:

class User {
    String username
    Set<Role> roles
}

In the application, I call SecurityUtils.getUser() to get the current logged-in user. This method returns a valid User instance if the user is logged in, or null if they are unauthenticated/anonymous:

User user = SecurityUtils.getUser()

I am trying to write a method where I need to determine if the user is logged in or not, and if they are, I need to do something special if their set of Roles are either empty or null:

if(user && !user.roles) {
    // Do something special
}

I would like to make this Groovier, so I tried:

if(!user?.roles) {
    // Do something special  
}

And this is not working. Again, the // Do something special should only execute if:

  1. The user is non-null (authenticated); and (
  2. Has a set of Roles that is null; or
  3. Has a set of Roles that is empty )

Any ideas?

Upvotes: 2

Views: 918

Answers (1)

Roman
Roman

Reputation: 6656

If user is null, then user?.roles evaluates to null, and !user?.roles evaluates to !null, which is true, so this conflicts with your first condition.

If user is not null, then user?.roles is equivalent to user.roles, and in this case all conditions are met.

Conclusion: use user && !user.roles. And I agree with comments, this is more readable.

Upvotes: 3

Related Questions