Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with Recursion and Generic Interfaces

I have three generic interfaces (with an inverses relationship between two of them) and want to process them in a recursive method:

public interface User<R extends Role<R,U>, U extends User<R,U>>
{
  public R getRole();
  public void setRole(R role);
}

public interface Role<R extends Role<R,U>,U extends User<R,U>>
{
  public List<R> getRoles();
  public void setRoles(List<R> roles);

  public List<U> getUser() ;
  public void setUser(List<U> user);
}

Now I want to do some processing with a recursion in my Worker class:

public <R extends Role<R,U>,U extends User<R,U>> void recursion(List<R> roles)
{
  for(R role : roles)
  {
    recursion(role.getRoles());
  }
}

I get this error and I'm didn't figured out why this does not work or how I can solve this:

Bound mismatch: The generic method recursion(List<R>) of type Worker is not
applicable for the arguments (List<R>). The inferred type User<R,User<R,U>>
is not a valid substitute for the bounded parameter <U extends User<R,U>>
like image 324
Thor Avatar asked Oct 25 '22 02:10

Thor


1 Answers

I modified it, without using generic wildcards ?, so it compiles.
After stripping out method declarations irrelevant to the problem:

public interface Role<R extends Role<R, U>, U extends User<R, U>> {
    public List<Role<R, U>> getRoles(); // Change here to return type
}

public interface User<R extends Role<R, U>, U extends User<R, U>> { // No change
}

// Change to method parameter type
public static <R extends Role<R, U>, U extends User<R, U>> void recursion(List<Role<R, U>> roles) {
    for (Role<R, U> role : roles) { // Change to element type
        recursion(role.getRoles());
    }
}

I hope these changes still fit your design - let me know if they don't work for you and I'll try to work around your requirements.

Phew! Tough one!

like image 175
Bohemian Avatar answered Oct 27 '22 11:10

Bohemian