Home > Software design >  How can rewrite about this java lambda expression? [duplicate]
How can rewrite about this java lambda expression? [duplicate]

Time:10-07

Currently I learn Springboot.

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> collection = new ArrayList<GrantedAuthority>();
        collection.add(()-> user.getRole().getKey());
        return collection;
    }

In this code

collection.add(()-> user.getRole().getKey());

I know this is lambda expression but I don't get raw code. This is not my code. Could you let me know the raw code?

CodePudding user response:

The code is hard to follow because the collection is supposed to be a collection of GrantedAuthority objects. A GrantedAuthority is a single method interface with a getAuthority() function - https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/GrantedAuthority.html#getAuthority()

So what the code is trying to do here is create a single element collection with a GrantedAuthority whose getAuthority method returns the value of user.getRole().getKey() - whatever that happens to be in this context.

You might find it easier to think of there being a single-use class here:

GrantedAuthority theOneAuthority = new GrantedAuthority() {
   String getAuthority() {
      return user.getRole().getKey();
   }
}
return List.of(theOneAuthority); // a single entry list

To understand the above, however, you'd need to understand the concept of an anonymous inner class - in other words a temporary type whose job it is to subclass an interface or other class to do something a particular method wants us to do.

In this instance, a lambda is a better alternative.

// as there's only one method, taking 0 parameters and returning string
// then this 0 parameter string-returning lambda can BE a `GrantedAuthority`
GrantedAuthority authFromLambda = () -> user.getRole().getKey();

CodePudding user response:

There are some types of lambda expressions:

  1. (int x, int y) -> { return x y; }
  2. x -> x * x
  3. ( ) -> x

So, your case is third one. It is used when you get no parameters as a method arguments and return a value. In your example, it just returns the value of user.getRole().getKey()); and it added to the Collection<GrantedAuthority>

  • Related