Search code examples
javamethodswarningschainingunchecked

Method chaining results in unchecked call warning


I have got the following interface which is implemented by the following class. For this class, I would like to be able to use method chaining, which is why I added a "return this" at the end of the addFilter() method:

public interface IFilteredDataService<B extends Bean> extends IDataService<B>
{
    FilteredDataService applyFilter(Predicate<B> filter);
}

public class FilteredDataService<B extends Bean> implements IFilteredDataService<B>
{
    @Override
    public FilteredDataService addFilter(Predicate<B> filter)
    {
        filters.add(filter);
        return this;
    }
}

When I use the addFilter() method in the following way, everything is fine:

someInstance.addFilter(foo);
someInstance.addFilter(bar);

When I use the method chaining like this:

someInstance.addFilter(foo).addFilter(bar);

it still works fine, but I get the following warning:

Unchecked call to 'addFilter(Predicate<B>)' as a member of raw type 'FilteredDataService'.

I was not able to figure out why this happens and how to remove it. Any help would be greatly appreciated.


Solution

  • You're missing the generic information in your return value, returning a raw (non-generic) FilteredDataService.

    Use public FilteredDataService<B> addFilter(Predicate<B> filter) to keep the generics.