Search code examples
javagenericstype-inferencehamcrest

How to hint type inference when using static imports?


I am using junit with hamcrest in my unit tests and I came across a generics problem:


assertThat(collection, empty());

I am aware of type inference not being available this way and that one of the solutions is to give a type hint, but how should I type hint when using static imports?


Solution

  • While type inference is not as powerful as we would like, in this case, it's really the API that's at fault. It unnecessarily restricts itself for no good reason. The is-empty matcher works on any collection, not just on collections of a specific E.

    Suppose the API is designed this way

    public class IsEmptyCollection implements Matcher<Collection<?>>
    {
        public static Matcher<Collection<?>> empty()
        {
            return new IsEmptyCollection();
        }
    }
    

    then assertThat(list, empty()) works as expected.

    You can try to convince the author to change the API. Meanwhile you can have a wrapper

    @SuppressWarnings("unchecked")
    public static Matcher<Collection<?>> my_empty()
    {
        return (Matcher<Collection<?>>)IsEmptyCollection.empty();
    }